哪个时候调用线程获得对象的内部锁?

时间:2013-07-21 11:51:28

标签: java thread-safety

这是我的班级

public class ThreadTest {
    public static void main(String[] args) {

        ThreadTest threadTest = new ThreadTest();
        threadTest.m1();
        synchronized (threadTest) {
            threadTest.m2();
        }
        System.out.println("End of main thread");
    }

    public void m1() {
        Thread myThread = new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    System.out.println(Thread.currentThread().getName() + " : " + i);
                }
                System.out.println("end of mythread");
            }
        });
        myThread.start();
    }

    public void m2() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " : " + i);
        }
    }

}

虽然我将我的代码放在synchronized块中但它似乎无法正常工作,并且两个for循环都是并行运行的。如何在多线程环境中将这些循环作为线程安全运行一个同步块。我给出了我的代码的错误是什么?

谢谢!

1 个答案:

答案 0 :(得分:4)

同步块可防止其他线程在同一对象上输入相同或另一个同步块。这里有一个同步块,只有一个线程进入它。所以所有其他线程都可以执行他们想要的任何内容。

相关问题