【发布时间】:2016-10-20 17:37:46
【问题描述】:
有人可以帮我解决这个多线程问题吗?
程序应该使用公共资源启动三个线程。每个线程都应该打印一个递增的计数值。示例输出如下所述。其中 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();
}
}
}
【问题讨论】:
-
酷!到目前为止,您尝试过什么?
-
@Nicolas 这是我的代码。执行主函数时抛出异常
标签: java multithreading