有人可以帮我解决这个多线程问题吗?
程序应该使用公共资源启动三个线程。每个线程应该打印递增的计数值。样本输出如下所述。其中T1,T2和T3是线程。
T1 T2 T3
1 2 3
4 5 6
7 8 9
我目前的代码:
public class RunnableSample implements Runnable {
static int count = 0;
public void run() {
synchronized (this) {
count++;
System.out.println(
"Current thread : Thread name :" + Thread.currentThread().getName()
+ " Counter value :" + count
);
}
}
}
//main method with for loop for switching between the threads
public class ThreadInitiator {
public static void main(String[] args) {
RunnableSample runnableSample = new RunnableSample();
Thread thread1 = new Thread(runnableSample, "T1");
Thread thread2 = new Thread(runnableSample, "T2");
Thread thread3 = new Thread(runnableSample, "T3");
for (int i = 0; i < 9; i++) {
thread1.start();
thread2.start();
thread3.start();
}
}
}
答案 0 :(得分:0)
创建一个同步方法来增加值。当一个方法被识别为synchronized时,一次只有一个线程可以访问它,而其他线程在它们可以访问该方法之前等待初始线程完成方法执行。
请检查How to synchronize a static variable among threads running different instances of a class in java?