[英]JAVA - make 10 threads run simultaneously to increment counter 1-10
I need 10 threads in JAVA to run simultaneously to increment counter from 1-10. 我需要10个线程才能同时运行以使计数器从1-10递增。
I have the code working. 我有代码在工作。 But, the counter is always in a different order. 但是,计数器始终处于不同的顺序。
public class Counter
{
static Thread[] threads = new Thread[10];
public static void main(String[] args)
{
Count c = new Count();
for(int i=0;i<10;i++)
{
threads[i] = new Thread(c);
threads[i].start();
}
}
}
public class Count implements Runnable {
int n=1;
@Override
public void run() {
System.out.println(n++);
}
public void showOutput(){
System.out.println(n++);
}
}
Output Example:2 4 3 1 5 9 8 6 7 10 输出示例:2 4 3 1 5 9 8 6 7 10
Threads are asynchronous and work independently. 线程是异步的并且独立工作。 There is no guanrantee of any order of execution of anything in different threads, unless there are some synchronization methods used . 除非使用某些同步方法,否则不保证在不同线程中执行任何命令的顺序 。 Your code works fine. 您的代码工作正常。
Use Join() function to run your threads in sync add the below code in your loop 使用Join()函数同步运行线程,在循环中添加以下代码
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Hope this helps! 希望这可以帮助!
Thanks -vivek 谢谢-vivek
You can use synchronized thread 您可以使用同步线程
@Override
public synchronized void run() {
System.out.println(n++);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.