我使用“for”循环生成100个线程来打印出数据0〜4。For循环生成的多线程不能使用同步?
public class ThreadTest implements Runnable {
static volatile int threadNum = 100;
public void run() {
synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);
}
}
}
public static void main(String[] args) {
for (int i = 0; i < threadNum; i++) {
ThreadTest t = new ThreadTest();
Thread t1 = new Thread(t);
t1.start();
}
}
}
我曾经希望为每个线程获取数据0〜4,因为“synchronized”只允许一个线程操作“for”循环。但是,打印结果并不如我预期的那样。
谁能帮我指向我们我的问题是什么?谢谢〜
提示:避免张贴屏幕截图。你的输出是“纯文本”;所以你简单地复制/粘贴该文本会容易得多。 – GhostCat