[英]JAVA - make 10 threads run simultaneously to increment counter 1-10
我需要10個線程才能同時運行以使計數器從1-10遞增。
我有代碼在工作。 但是,計數器始終處於不同的順序。
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++);
}
}
輸出示例:2 4 3 1 5 9 8 6 7 10
線程是異步的並且獨立工作。 除非使用某些同步方法,否則不保證在不同線程中執行任何命令的順序 。 您的代碼工作正常。
使用Join()函數同步運行線程,在循環中添加以下代碼
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
希望這可以幫助!
謝謝-vivek
您可以使用同步線程
@Override
public synchronized void run() {
System.out.println(n++);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.