终止线程的典型方式:
终止线程我们一般不使用JDK提供的stop()/destroy()方法(它们本身也被JDK废弃了)。通常的做法是提供一个boolean型的终止变量,当这个变量置为false,则终止线程的运行。
终止线程的典型方法:
public class TestThreadCiycle implements Runnable { String name; boolean live = true;// 标记变量,表示线程是否可中止; public TestThreadCiycle(String name) { super(); this.name = name; } public void run() { int i = 0; //当live的值是true时,继续线程体;false则结束循环,继而终止线程体; while (live) { System.out.println(name + (i++)); } } public void terminate() { live = false; } public static void main(String[] args) { TestThreadCiycle ttc = new TestThreadCiycle("线程A:"); Thread t1 = new Thread(ttc);// 新生状态 t1.start();// 就绪状态 for (int i = 0; i < 100; i++) { System.out.println("主线程" + i); } ttc.terminate(); System.out.println("ttc stop!"); } }
执行结果如图所示:(因为是多线程,故每次运行结果不一定一致)
暂停线程执行sleep/yield:
暂停线程执行常用的方法有sleep()和yield()方法,这两个方法的区别是:
1. sleep()方法:可以让正在运行的线程进入阻塞状态,直到休眠时间满了,进入就绪状态。
2. yield()方法:可以让正在运行的线程直接进入就绪状态,让出CPU的使用权。
暂停线程的方法-sleep():
public class TestThreadState { public static void main(String[] args) { StateThread thread1 = new StateThread(); thread1.start(); StateThread thread2 = new StateThread(); thread2.start(); } } //使用继承方式实现多线程 class StateThread extends Thread { public void run() { for (int i = 0; i < 100; i++) { System.out.println(this.getName() + ":" + i); try { Thread.sleep(2000);//调用线程的sleep()方法; } catch (InterruptedException e) { e.printStackTrace(); } } } }
执行结果如图11-6所示(注:以下图示只是部分结果,运行时可以感受到每条结果输出之前的延迟,是Thread.sleep(2000)语句在起作用):
暂停线程的方法-yield():
public class TestThreadState { public static void main(String[] args) { StateThread thread1 = new StateThread(); thread1.start(); StateThread thread2 = new StateThread(); thread2.start(); } } //使用继承方式实现多线程 class StateThread extends Thread { public void run() { for (int i = 0; i < 100; i++) { System.out.println(this.getName() + ":" + i); Thread.yield();//调用线程的yield()方法; } } }
运行效果:
注:以下图示只是部分结果,可以引起线程切换,但运行时没有明显延迟


