yiled():让步
wait():等待
sleep():休眠
yiled是让步,会使当前线程由运行状态进入到就绪状态,让其他优先级高线程先执行,但是如果是同一优先级的线程,那么谁先执行就不确定了.它不会释放锁
wailt等待,会使当前线程进入阻塞状态,并且会释放锁
sleep()休眠,会使当前线程进入休眠阻塞状态,但不会释放锁
下面通过示例演示sleep()是不会释放锁的。
1 // SleepLockTest.java的源码
2 public class SleepLockTest{
3
4 private static Object obj = new Object();
5
6 public static void main(String[] args){
7 ThreadA t1 = new ThreadA("t1");
8 ThreadA t2 = new ThreadA("t2");
9 t1.start();
10 t2.start();
11 }
12
13 static class ThreadA extends Thread{
14 public ThreadA(String name){
15 super(name);
16 }
17 public void run(){
18 // 获取obj对象的同步锁
19 synchronized (obj) {
20 try {
21 for(int i=0; i <10; i++){
22 System.out.printf("%s: %d\n", this.getName(), i);
23 // i能被4整除时,休眠100毫秒
24 if (i%4 == 0)
25 Thread.sleep(100);
26 }
27 } catch (InterruptedException e) {
28 e.printStackTrace();
29 }
30 }
31 }
32 }
33 }
运行结果:
t1: 0
t1: 1
t1: 2
t1: 3
t1: 4
t1: 5
t1: 6
t1: 7
t1: 8
t1: 9
t2: 0
t2: 1
t2: 2
t2: 3
t2: 4
t2: 5
t2: 6
t2: 7
t2: 8
t2: 9
结果说明:
主线程main中启动了两个线程t1和t2。t1和t2在run()会引用同一个对象的同步锁,即synchronized(obj)。在t1运行过程中,虽然它会调用Thread.sleep(100);但是,t2是不会获取cpu执行权的。因为,t1并没有释放“obj所持有的同步锁”!