Java 线程(一)
interrupt () 可以终止线程,略显粗暴。(比起stop() 还是温柔一些 = = .orz )
介绍一种不用interrupt()终止线程的方法。
public class TestThread4{ public static void main(String []args) { Runner4 r = new Runner4(); //创建实现了Runnable Interface的类的实例 Thread t = new Thread(r); //根据Thread Constructor ,传入Runnable 参数。此处有多态(父类引用指向子类,该处为接口类型指向实现接口的类,重写,实现) t.start(); //Thread.start()会自动调用传入Runnable Obj 的 run() 此语句,t 和 main 两个Thread 运行 for(int i=0; i<10000; i++) { if(i % 1000 ==0 & i > 0){ System.out.println("in thread main i =" + i); } } System.out.println("Thread main is over"); r.shutDown(); //当main执行完后,调用实现Runnable Interface的shutDown()来终止Thread t } } class Runner4 implements Runnable { private boolean flag = true; public void run(){ int i = 0; while(flag == true){ //run()运行的条件为flat == true , run()条件不满足,run()结束,Thread结束 System.out.println(" " + i++); } } public void shutDown(){ flag = false; //修改boolean 使run()结束 } }
in thread main i =1000 0 in thread main i =2000 1 2 3 in thread main i =3000 4 in thread main i =4000 5 6 7 8 9 10 11 in thread main i =5000 in thread main i =6000 12 13 in thread main i =7000 in thread main i =8000 14 15 in thread main i =9000 16 Thread main is over 17
内存布局如图所示: