代码
package per.thread;
import java.io.IOException;
public class Test {
private int i = 0;
private Object object = new Object();
public static void main(String[] args) throws IOException {
Test test = new Test();
Test.MyThread thread1 = test.new MyThread();
Test.MyThread thread2 = test.new MyThread();
thread1.start();
thread2.start();
}
class MyThread extends Thread{
@Override
public void run() {
synchronized (object) {
i++;
System.out.println("i:"+i);
try {
System.out.println("线程"+Thread.currentThread().getName()+"进入睡眠状态");
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
// TODO: handle exception
}
System.out.println("线程"+Thread.currentThread().getName()+"睡眠结束");
i++;
System.out.println("i:"+i);
}
}
}
}
实现
i:1
线程Thread-0进入睡眠状态
线程Thread-0睡眠结束
i:2
i:3
线程Thread-1进入睡眠状态
线程Thread-1睡眠结束
i:4
分析
在thread1休眠之后,thread2没有立即执行,因为给object加了synchronized。