1

here is my class

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);
        }
    }

}

Although i put my code inside synchronized block it doesn't seem to work properly and both of for loops are run parallelly.How can i run those loops as threadsafe in multi-threaded environment with a synchronized block.Where is the mistake i made my code given?

thanks!

4

1 回答 1

4

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

于 2013-07-21T11:54:08.843 回答