守护线程-setDaemon:将该线程标记为守护线程或用户线程(后台线程),当正在运行的线程都是守护线程时,Java 虚拟机退出。该方法必须在启动线程前调用
1 class StopThread implements Runnable{ 2 private boolean flag = true; 3 public synchronized void run(){ 4 while(flag){ 5 try{ 6 wait();//t0 t1 使用这个方法是强制性唤醒的会发生异常,就执行catch里的代码,然后将标记改为false 7 }catch (InterruptedException e){ 8 System.out.println(Thread.currentThread().getName()+"....."+e); 9 flag = false; 10 } 11 12 System.out.println(Thread.currentThread().getName()+"......++++"); 13 } 14 } 15 public void setFlag(){ 16 flag = false; 17 } 18 } 19 class StopThreadDemo { 20 public static void main(String[] args) { 21 StopThread st = new StopThread(); 22 23 Thread t1 = new Thread(st); 24 Thread t2 = new Thread(st); 25 26 t1.start(); 27 t2.setDaemon(true);//将t2设为守护线程 28 t2.start(); 29 30 31 int num = 1; 32 for(;;){ 33 if(++num==50){ 34 t1.interrupt(); 35 t2.interrupt(); 36 break; 37 } 38 System.out.println("main...."+num); 39 } 40 System.out.println("over"); 41 } 42 }
1 class Demo implements Runnable{ 2 public void run(){ 3 for(int x=0; x<50; x++){ 4 System.out.println(Thread.currentThread().toString()+"....."+x); 5 Thread.yield();//暂停当前线程,让其他线程执行 6 } 7 } 8 } 9 10 class JoinDemo 11 { 12 public static void main(String[] args) throws Exception 13 { 14 Demo d = new Demo(); 15 16 Thread t1 = new Thread(d); 17 Thread t2 = new Thread(d); 18 19 t1.start(); 20 21 22 t2.start(); 23 // t2.setPriority(Thread.MAX_PRIORITY);//设置线程的优先级 24 25 // t1.join();//t1线程启动后要申请加入进来,运行。主线程释放运行资格暂停运行,等t1线程运行完终止后主线程才运行临时加入一个线程运算时可以使用join方法。 26 27 for(int x=0; x<50; x++){ 28 System.out.println(Thread.currentThread()+"....."+x); 29 } 30 } 31 }