LifeCycle(生命周期)

生命周期

  • 新生
  • 可运行(runable,running)
  • 阻塞
  • 死亡

相关方法

就绪:
start()
挂起/唤醒
suspend/resume
native wait/notify
sleep
终止线程
stop()
interrupt()
状态:
boolean isAlive()
boolean isInterrupted()
static boolean interrupted

挂起和唤醒

suspend/resume和sleep区别:

  • suspend/resume方式不建议使用
  • suspend/resume和sleep最大的区别,前者可以在当前线程挂起其他的线程,sleep是使当前线程睡眠。
  • sleep同wait区别,sleep是抱着资源睡觉,wait是等待,

    sleep睡醒过后是等待调度,wait是直接唤醒进入到运行中(待考证)
/**
 * 挂起和唤醒线程
 * @author 98543
 */
public class SuspResu extends Thread{
	
	class SleepThread extends Thread{
		public void run() {
			try {
				sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("睡觉,睡了二秒");
		}
	}
	
	public void run() {
		while(true) {
			try {
				sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(System.currentTimeMillis());
		}
	}

	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws InterruptedException {
		SuspResu sr = new SuspResu();
		SleepThread st = sr.new SleepThread();
		st.start();
		st.join();
		boolean flag = false;
		sr.start();
		while (true) {
			sleep(5000);   // 主线程睡眠五秒
			flag = !flag; 
			if(flag) {
				System.out.println("线程等待");
				sr.suspend();
			}else { 
				System.out.println("线程唤醒");
				sr.resume();
			}
		}
	}
}

终止线程

  1. 标识终止
  2. interrup方法终止()
      如果线程处于sleep状态,会报错interrupException异常。
      在Thread类中有两个方法可以判断线程是否通过interrupt方法被终止。一个是静态的方法interrupted(),一个是非静态的方法isInterrupted(),这两个方法的区别是interrupted用来判断当前线是否被中断,而isInterrupted可以用来判断其他线程是否被中断。
  3. stop方法终止(不建议使用)
public class ExitByFlag {
	
 	static class ExitThread extends Thread{
		public volatile boolean exit = true;
		public void run() {
			 while(exit) { 
				 try {
					Thread.sleep(2000);
					System.out.println("骑上我心爱的小摩托");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			 }
		}
		
		public ExitThread() {}
	}

	public static void main(String[] args) throws InterruptedException, IOException {
		ExitThread t = new ExitThread();
		t.start();
		System.out.println("按任意键退出");
		System.in.read();
		t.exit = false;
		t.join(3000);
		System.out.println("线程已退出");
	}
}

扩展

native关键字

volatile关键字

线程通信

https://blog.csdn.net/u013394527/article/details/80560153

posted @ 2019-10-21 09:44  kungFuPander  阅读(676)  评论(0编辑  收藏  举报