文章目录
BLOCKED WAITING TIMED_WAITING代码演示
- BLOCKED WAITING TIMED_WAITING代码演示
如下的代码为 演示打印出 BLOCKED WAITING TIMED_WAITING 的示例 . 创建出两个线程. 同时去竞争private synchronized void syn()
同步方法. 一个方法进入了, 由于执行了Thread.sleep(1000);wait();
两个方法. 因此会分别打印出 TIMED_WAITING 状态 和 BLOCKED 状态 .
线程二由于线程一占用了private synchronized void syn()
同步方法 , 无法获得锁, 因此会打印出 BLOCKED 状态 .
其中主线程的Thread.sleep(5);
和Thread.sleep(1000);
分别是初始的时候, 把线程资源给线程1 和让线程1 休眠完成.
package com.thread.sixstates;
/**
* 类名称:BlockedWaitingTimedWaiting
* 类描述: 打印出 Blocked Waiting TimedWaiting 状态
*
* @author: https://javaweixin6.blog.csdn.net/
* 创建时间:2020/8/29 13:58
* Version 1.0
*/
public class BlockedWaitingTimedWaiting implements Runnable {
public static void main(String[] args) {
BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
Thread thread1 = new Thread(runnable);
thread1.start();
Thread thread2 = new Thread(runnable);
thread2.start();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
//thread1为 TIMED_WAITING 状态 因为执行了 Thread.sleep(1000);
System.out.println(thread1.getState());
//thread2为 BLOCKED 状态 因为此时 上一个线程进入synchronized 代码块中不出来, 无法获得锁
System.out.println(thread2.getState());
try {
Thread.sleep(1300);
} catch (InterruptedException e) {
e.printStackTrace();
}
//thread1为 WAITING 状态 因为执行了wait();
System.out.println(thread1.getState());
}
@Override
public void run() {
syn();
}
/**
* 此synchronized 代码块的作用是
* 让一个线程 Thread.sleep(1000); 进入 timed waiting 状态
* 让一个线程 进入blocked 状态. 因为此时 上一个线程进入synchronized 代码块中不出来, 无法获得锁
*/
private synchronized void syn() {
try {
// TIMED_WAITING 状态
Thread.sleep(1000);
//WAITING 状态
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
控制台打印如下 :