優先順序和守護執行緒
阿新 • • 發佈:2022-04-13
優先順序
package com.lei.state; //測試執行緒優先順序 public class TestPriority { public static void main(String[] args) throws InterruptedException { //主執行緒預設優先順序 System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority()); MyPriority myPriority=new MyPriority(); Thread t1=new Thread(myPriority); Thread t2=new Thread(myPriority); Thread t3=new Thread(myPriority); Thread t4=new Thread(myPriority); Thread t5=new Thread(myPriority); Thread t6=new Thread(myPriority); //先設定優先順序在啟動 t1.start(); //不設定延遲的話cpu跑得太快,不會按照優先順序 Thread.sleep(2000); t2.setPriority(1); t2.start(); t3.setPriority(4); t3.start(); t4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10 t4.start(); //錯誤 // t5.setPriority(-1); // t5.start(); // // t6.setPriority(11); // t6.start(); } } class MyPriority implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority()); } }
守護執行緒
package com.lei.state; import com.sun.xml.internal.stream.util.ThreadLocalBufferAllocator; //測試守護執行緒 //上帝守護你 public class TestDaemon { public static void main(String[] args) { God god = new God(); You you = new You(); Thread thread = new Thread(god); thread.setDaemon(true);//預設是false表示使用者執行緒,正常的執行緒都是使用者執行緒 thread.start(); new Thread(you).start(); } } //上帝 class God implements Runnable{ @Override public void run() { while(true){ System.out.println("上帝保護你"); } } } //你 class You implements Runnable{ @Override public void run() { for (int i = 0; i < 36500; i++) { System.out.println("你一生都開心的活著"); } System.out.println("=====GoodBye World!====="); } }