不推荐使用jdk提供的stop(),destory()方法,可自定义公开stop()方法,通过设置标志位让其停止。
public class Stop implements Runnable { private boolean flag = true; @Override public void run() { int i = 0; while (flag){ System.out.println("running..."+i++); } } public void stop(){ this.flag = false; } public static void main(String[] args) { Stop s = new Stop(); new Thread(s).start(); for (int i = 0; i < 100 ; i++) { if (i == 75){ s.stop(); System.out.println("stop..."); } System.out.println("main"+i); } } }
sleep()指定当期线程阻塞的毫秒数,时间达到后进入就绪状态。每一个对象都有一个锁,sleep不释放锁。
public class Sleep { public static void main(String[] args) { Date start = new Date(System.currentTimeMillis()); // 获取系统当前时间 while (true){ try { Thread.sleep(1000); System.out.println(new SimpleDateFormat("HH:mm:ss").format(start)); start = new Date(System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } } }
暂停执行当前线程,转为就绪状态,系统执行去执行其他线程,但具体执行哪个线程由调度器决定。
public class Yield implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"线程开始执行"); Thread.yield(); System.out.println(Thread.currentThread().getName()+"线程暂停执行"); } public static void main(String[] args) { Yield y = new Yield(); new Thread(y,"a").start(); new Thread(y,"b").start(); } }
指定的线程合并到当前执行的线程中,即交替执行转为顺序执行,待该指定线程执行完之后,再执行其他线程,此时其他线程阻塞。
public class Join implements Runnable{ @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("thread"+i); } } public static void main(String[] args) throws InterruptedException { Join j = new Join(); Thread t = new Thread(j); t.start(); for (int i = 0; i < 200; i++) { if (i == 88){ t.join(); } System.out.println("main"+i); } } }
一个线程可以在给定时间点处于一个状态。 这些状态是不反映任何操作系统线程状态的虚拟机状态。
通过Thread.getState()获取线程状态
public class State implements Runnable{ @Override public void run() { for (int i = 0; i < 6; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("thread"); } public static void main(String[] args) { State s = new State(); Thread t = new Thread(s); Thread.State state = t.getState(); // 获取线程状态 System.out.println(state); t.start(); state = t.getState(); System.out.println(state); while (state != Thread.State.TERMINATED){ try { Thread.sleep(100); state = t.getState(); System.out.println(state); } catch (InterruptedException e) { e.printStackTrace(); } } } }