您的位置:首页 > 其它

线程的几种状态及相关方法使用

2018-08-24 17:05 344 查看

新建(new)

  新建一个线程的对象。

可运行(runable)

  线程对象创建后,其他线程调用该线程的start方法。或者该线程位于可运行线程池中等待被线程调用,已获取cpu的使用权。

运行(running)

  可运行的线程获取了cpu的使用权,执行程序代码/

阻塞(block)

  由于某些原因该线程放弃了cpu的使用权。停止执行。除非线程进入可运行的状态,才会有机会获取cpu的使用权。

  1. 等待阻塞:运行中的线程执行wait方法,这时候该线程会被放入等待队列。

  2. 同步阻塞:运行中的线程获取同步锁,如果该同步锁被别的线程占用,这个线程会成被放入锁池,等待其他线程释放同步锁。

  3. 其他阻塞:运行的线程执行sleep或者join方法这个线程会成为阻塞状态。当sleep超时,join等待线程终止,该线程会进入可运行状态。

死亡(dead)

  线程run mian 执行完毕后,或者因为某些异常产生退出了 run 方法,该线程的生命周期结束。



wait、notify依次打印

public class Test {

public static void main(String[] args) {
Object a = new Object();
Object b = new Object();
Object c = new Object();
Thread t1 = new Thread(new Print(a, b, "A"));
Thread t2 = new Thread(new Print(b, c, "B"));
Thread t3 = new Thread(new Print(c, a, "C"));
t1.start();
t2.start();
t3.start();
}

}

class Print implements Runnable {
Object self;
Object next;
String str;

public Print(Object self, Object next, String str) {
this.self = self;
this.next = next;
this.str = str;
}

@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (self) {
synchronized (next) {
System.out.println(str);
next.notify();
}
try {
if (i == 9) {
return;
}
self.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐