【发布时间】:2018-07-28 16:30:09
【问题描述】:
我正在尝试在 for 循环上使用同步,从技术上讲,for 循环应该由一个线程完全执行,然后才允许下一个线程执行。
我声明了 3 个线程,然后执行它,但我同时获得了 3 个线程的输出。
请找到我的以下代码:
public class Sample {
public static void main(String[] args) {
DummyForSample1 t1 = new DummyForSample1();
t1.setName("1st");
t1.start();
DummyForSample1 t2 = new DummyForSample1();
t2.setName("2nd");
t2.start();
DummyForSample1 t3 = new DummyForSample1();
t3.setName("3rd");
t3.start();
}
}
public class DummyForSample1 extends Thread {
public void run(){
System.out.println("its execting " +
Thread.currentThread().getName());
forloop();
}
synchronized void forloop() {
for (int i=0;i<10;i++) {
System.out.println(Thread.currentThread().getName()+ " " + i);
}
}
}
这是输出:
its execting 2nd
its execting 3rd
its execting 1st
3rd 0
3rd 1
3rd 2
3rd 3
3rd 4
3rd 5
3rd 6
3rd 7
2nd 0
3rd 8
1st 0
1st 1
1st 2
1st 3
1st 4
3rd 9
2nd 1
2nd 2
2nd 3
2nd 4
2nd 5
1st 5
2nd 6
1st 6
2nd 7
1st 7
2nd 8
1st 8
2nd 9
1st 9
【问题讨论】:
-
synchronized锁定当前对象的监视器。您有不同的实例,因此synchronized什么都不做。 -
请参阅链接中的示例,了解如何使用外部线程对象。 producer_consumer
标签: for-loop concurrency synchronization