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);
}
}
}
输出:
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
为什么在执行第一个同步块时即使锁对象不同也不能Thread2
执行run()
方法中的第二个同步块。执行是否在第一个同步块处等待直到离开该块?Thread1
Thread2
Thread1
如果是这样如何使两个同步块同时运行?