package com.dq;
public class ThreadTest implements Runnable
{
@Override
public void run()
{
// 线程1先进这个方法,当线程1睡眠时,线程2没有得到锁,于是它的状态为BLOCKED
synchronized (this)
{
System.out.println(Thread.currentThread().getName() + " 线程执行中,此时外面等待线程的状态为BLOCKED");
try
{
Thread.sleep(1000); // 线程1运行到此处时状态是TIMED_WAITING
wait(); // 线程运行到此处时线程状态为WAITING
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException
{
ThreadTest task = new ThreadTest();
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
//这里休眠一小会是为了有机会执行线程1,线程1执行时进入了休眠状态
Thread.sleep(22);
System.out.println("线程1状态: " + thread1.getState());
thread2.start();
// 这里再次休眠是为了线程2获得运行的机会,它运行run方法但没有获得锁,于是状态为BLOCKED
Thread.sleep(22);
System.out.println("线程2状态: " + thread2.getState());
// 这里休眠1200是为了让线程run方法的休眠时间过时,此时执行wait方法,线程进入等待状态WAITING
Thread.sleep(1200);
System.out.println("线程1状态: " + thread1.getState());
}
}
代码演示线程的TIMED_WAITING,BLOCKED,WAITING状态
最新推荐文章于 2023-09-15 09:38:26 发布