Java Thread State

public class ThreadState implements Runnable {
	public synchronized void waitForASecond() throws InterruptedException {
		wait(500); // 使当前线程等待0.5秒或其他线程调用notify()或notifyAll()方法
	}

	public synchronized void waitPermenant() throws InterruptedException {
		wait(); // 使当前线程永久等待,直到其他线程调用notify()或notifyAll()方法
	}

	public synchronized void notifyNow() throws InterruptedException {
		notify(); // 唤醒由调用wait()方法进入等待状态的线程
	}

	public void run() {
		try {
			waitForASecond(); // 在新线程中运行waitForASecond()方法
			waitPermenant(); // 在新线程中运行waitPermenant()方法
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

public class Test {
	public static void main(String[] args) throws InterruptedException {
		ThreadState state = new ThreadState();// 创建State对象
		Thread thread = new Thread(state);// 利用State对象创建Thread对象
		System.out.println("新建线程:" + thread.getState());// 输出线程状态
		thread.start(); // 调用thread对象的start()方法,启动新线程
		System.out.println("启动线程:" + thread.getState());// 输出线程状态
		Thread.sleep(100); // 当前线程休眠0.1秒,使新线程运行waitForASecond()方法
		System.out.println("计时等待:" + thread.getState());// 输出线程状态
		Thread.sleep(1000); // 当前线程休眠1秒,使新线程运行waitForYears()方法
		System.out.println("等待线程:" + thread.getState());// 输出线程状态
		state.notifyNow(); // 调用state的notifyNow()方法
		System.out.println("唤醒线程:" + thread.getState());// 输出线程状态
		Thread.sleep(1000); // 当前线程休眠1秒,使新线程结束
		System.out.println("终止线程:" + thread.getState());// 输出线程状态
	}
}

新建线程:NEW
启动线程:RUNNABLE
计时等待:TIMED_WAITING
等待线程:WAITING
唤醒线程:BLOCKED
终止线程:TERMINATED

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值