Java多线程同步不适用于此for循环

时间:2018-07-28 16:30:10

标签: for-loop concurrency synchronization

我正在尝试在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

1 个答案:

答案 0 :(得分:0)

您在方法上使用synchronised关键字。这意味着您正在对当前对象实例进行同步。由于您有'DummyForSample1'的三个不同实例,因此不会阻止线程同时输入相同的方法。

确保所有线程都使用同一对象进行锁定。在您的示例中,您可以使用静态成员来实现此目标,如下所示:

public class DummyForSample1 extends Thread {

    private static final Object lock = new Object();

    public void run() {
        System.out.println("its execting      " +
                Thread.currentThread().getName());
        forloop();
    }

    void forloop() {
        synchronized (lock) {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "    " + i);
            }
        }
    }
}