线程优先级、守护线程
一、线程优先级
线程优先级的设置能让优先级高的线程先运行,不过并不是绝对的。主要还是取决于CPU的调度
1.线程优先级测试实例
//线程优先级 public class ThreadDemo12_priority { public static void main(String[] args) { //打印主线程优先级(系统默认为5) System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority()); MyPriority mp=new MyPriority(); Thread t1=new Thread(mp); Thread t2=new Thread(mp); Thread t3=new Thread(mp); Thread t4=new Thread(mp); Thread t5=new Thread(mp); Thread t6=new Thread(mp); //先设置优先级,再启动 t1.start();//不设置优先级,默认为5 t2.setPriority(1); t2.start(); t3.setPriority(2); t3.start(); t4.setPriority(3); t4.start(); t5.setPriority(8); t5.start(); t6.setPriority(Thread.MAX_PRIORITY); t6.start(); } } class MyPriority implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority()); } }
二、线程守护
//守护线程 //我生前上帝线程会跟着我运行,我死后上帝线程也会结束 public class ThreadDemo13_daemon { public static void main(String[] args) { MyLife me=new MyLife(); God god=new God(); Thread thread=new Thread(god); thread.setDaemon(true);//daemon默认是为false thread.start(); new Thread(me).start(); } } //这是上帝线程 class God implements Runnable { @Override public void run() { while (true) { try { Thread.sleep(50); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("我是上帝,守护着你"); } } } //这是自己 class MyLife implements Runnable{ @Override public void run() { for (int i = 0; i < 5; i++) { try { Thread.sleep(50); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("我开心的活着"); } System.out.println("我死了============"); }