1.sleep()和wait方法的区别
<1>,sleep()是Thread类的静态方法方法,wait()是Object的实例方法
<2>.sleep()不释放锁,其他线程,仍然无法访问这个对象,只是让出cpu的执行权,wait()释放锁,持有的线程会进入等待池中,等待被唤醒,唤醒以后需要重新竞争锁。
<3>.sleep()不需要被唤醒,不涉及线程之间的通信,wait()需要被notify()或者notifyAll()
<4>.wait()需要放在同步代码块中,sleep()不需要
共同点:
他们都可以被中断,被中断都产生异常。
释放锁不释放锁验证代码:
public class ContrastSleepWait extends Thread {
public synchronized void sleepMethod(){
System.out.println("sleep start----- "+Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sleep end----- "+Thread.currentThread().getName());
}
public synchronized void waitMethod(){
System.out.println("wait start----- "+Thread.currentThread().getName());
//区别wait必须放在同步代码块里
synchronized (this){
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("wait end----- "+Thread.currentThread().getName());
}
public static void main(String[] args){
final ContrastSleepWait sleepWaitOne = new ContrastSleepWait();
for (int i = 0; i <5 ; i++) {
/**
* lambada表达式 等于
* new Thread(){
* public void run(){
* sleepWaitOne.sleepMethod();
* }
* }.start();
* */
new Thread(()->sleepWaitOne.sleepMethod()).start();
}
//等待十秒,等上面方法执行完成
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-----------这是分隔符------------");
final ContrastSleepWait sleepWaitTwo = new ContrastSleepWait();
for (int i = 0; i <5 ; i++) {
new Thread(()->sleepWaitOne.waitMethod()).start();
}
}
}
打印结果如下:
sleep start----- Thread-1
sleep end----- Thread-1
sleep start----- Thread-5
sleep end----- Thread-5
sleep start----- Thread-4
sleep end----- Thread-4
sleep start----- Thread-3
sleep end----- Thread-3
sleep start----- Thread-2
sleep end----- Thread-2
-----------这是分隔符------------
wait start----- Thread-7
wait start----- Thread-8
wait start----- Thread-9
wait start----- Thread-10
wait start----- Thread-11
wait end----- Thread-11
wait end----- Thread-8
wait end----- Thread-7
wait end----- Thread-10
wait end----- Thread-9
2.线程的生命周期
<1>新建(4种创建线程周期的方法)
<2>就绪 调用start()方法后进入就绪态或者线程被notify()、notifyAll()唤醒进入就绪态
<3>运行 当线程获取锁的时候,进入运行态
<4>阻塞 当调用sleep(),wait()方法时进入
<5>死亡