`

线程池准备工作判断线程是否正在被使用

阅读更多
package com.ijo.server;
/**
 * 经测试分析当线程处于 运行和阻塞状态 isAlive都返回 true 依次类推当处于死锁也是一样的
 * 故可以作为线程是否被正在使用的判断依据,是离线程池判断又进一步的了
 * @author Administrator
 *
 */
public class ThreadAliveDemo {

	public static void main(String[] args) throws InterruptedException {
		Work work = new Work();
		System.out.println("start before " + work.isAlive());
		work.start();
		System.out.println("start after " + work.isAlive());
		Thread.sleep(2000);
		System.out.println("runing finshed " + work.isAlive());
		work.notifyWork();
		System.out.println("notify " + work.isAlive());
	}
}

class Work extends Thread {

	@Override
	public void run() {
		synchronized (this) {
			try {
				Thread.sleep(1000);
				wait();
				System.out.println("run .....");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public void notifyWork() {
		synchronized (this) {
			notify();
		}
	}

}

 

运行结果:

start before false
start after true
runing finshed true
run .....
notify false 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics