线程同步行为

tez*_*tez 1 java multithreading synchronized

class Untitled {
    public static void main(String[] args) {
        MyRunnable r1 = new MyRunnable();
        Thread t1 = new Thread(r1,"Thread 1:");
        Thread t2 = new Thread(r1,"Thread 2:");
        t1.start();
        t2.start();

    }
}

class MyRunnable implements Runnable
{
    String s1 = "Hello World";
    String s2 = "Hello New World";
    public void run()
    {
        synchronized(s1)
        {
            for(int i =0;i<3;++i)
            System.out.println(Thread.currentThread().getName()+s1);

        }
        synchronized(s2)
        {
            for(int i = 0;i<3;++i)
            System.out.println(Thread.currentThread().getName()+s2);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

Thread 1:Hello World
Thread 1:Hello World
Thread 1:Hello World
Thread 1:Hello New World
Thread 2:Hello World
Thread 1:Hello New World
Thread 2:Hello World
Thread 1:Hello New World
Thread 2:Hello World
Thread 2:Hello New World
Thread 2:Hello New World
Thread 2:Hello New World
Run Code Online (Sandbox Code Playgroud)

为什么Thread2在执行第一个同步块时,即使锁定对象不同,也不能在run()方法中执行第二个同步块.Thread1是否在第一个同步块Thread2执行等待直到Thread1离开该块?

如果是这样,如何使两个同步块同时运行?

ass*_*ias 6

Thread2的执行是否在第一个同步块中等待,直到Thread1离开该块?

是的,这是主意 - thread2一个接一个地执行块.如果它被阻止但无法进入第一个,它将在那里等待直到s1锁定可用.

如果是这样,如何使两个同步块同时运行?

您需要将它们拆分为两个不同的runnable,并为每个runnable使用一个线程.