public final void join() throws InterruptedException { join(0);}public final synchronized void join(long millis) throws InterruptedException { ... if (millis == 0) { while (isAlive()) { wait(0); } } else { ... } }
LockSuppport.park()/unpark(Thread) 支持唤醒指定线程
public class ParkThread extends Thread{ @Override public void run() { System.out.println("doing...."); LockSupport.park(); //进入waiting System.out.println("unpack continue doing..."); } public static void main(String[] args) throws InterruptedException { ParkThread parkThread = new ParkThread(); parkThread.start(); Thread.sleep(5000); //休眠5s LockSupport.unpark(parkThread); //唤醒 }}
Thread.sleep(long) 休眠不开释锁, 时间到了主动唤醒
二、线程启动/制止/制止
线程启动支持两种方式:(1)继续Thread (2)实现Runnable接口
class MyThread extends Thread{ public void run(){ ... }}MyThread p = new MyThread();p.start();class MyJob implements Runable{ public void run(){ ... }}new Thread(new MyJob()).start();
优雅制止线程方式:自界说标记位和制止标记位
public class StopThread extends Thread{ private volatile boolean exit = false; private long count = 0; @Override public void run() { while (!exit && !Thread.currentThread().isInterrupted()){ count ++; } System.out.println(Thread.currentThread().getName()+ " count:" + count); } public void cancel(){ this.exit = true; } public static void main(String[] args) throws InterruptedException { StopThread stopThread1 = new StopThread(); stopThread1.setName("FlagThread"); stopThread1.start(); StopThread stopThread2 = new StopThread(); stopThread2.setName("InterruptedThread"); stopThread2.start(); Thread.sleep(20); stopThread1.cancel(); //自界说标记位 Thread.sleep(10); stopThread2.interrupt();//制止标记位 }}