线程的礼让
利用Thread.yield()使线程进行礼让
礼让的概念:
-
礼让线程,让当前正在执行的线程暂停,但并不是阻塞
-
将线程从运行状态转化为就绪状态
-
线程礼让是由cpu调度,并不一定成功
1 public class TestYield { 2 3 public static void main(String[] args) { 4 MyYield myYield = new MyYield(); 5 new Thread(myYield,"a").start(); 6 new Thread(myYield,"b").start(); 7 } 8 } 9 10 class MyYield implements Runnable{ 11 12 @Override 13 public void run() { 14 System.out.println(Thread.currentThread().getName()+ "线程开始执行"); 15 Thread.yield();//礼让 16 System.out.println(Thread.currentThread().getName()+ "线程停止执行"); 17 } 18 }
线程的优先级
设置线程的优先级
更改线程的优先级
其中main线程的优先级默认为5
1 public class TestPriority { 2 public static void main(String[] args) { 3 //主线程优先级 4 System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority()); 5 MyPriority myPriority = new MyPriority(); 6 Thread t1 = new Thread(myPriority); 7 Thread t2 = new Thread(myPriority); 8 Thread t3 = new Thread(myPriority); 9 Thread t4 = new Thread(myPriority); 10 Thread t5 = new Thread(myPriority); 11 Thread t6 = new Thread(myPriority); 12 Thread t7 = new Thread(myPriority); 13 14 //设置优先级,在启动 15 t1.start(); 16 17 t2.setPriority(1); 18 t2.start(); 19 20 t3.setPriority(4); 21 t3.start(); 22 23 t4.setPriority(Thread.MAX_PRIORITY); 24 t4.start(); 25 26 // t5.setPriority(-1); 27 // t5.start(); 28 // 29 // t6.setPriority(11); 30 // t6.start(); 31 } 32 } 33 class MyPriority implements Runnable{ 34 35 @Override 36 public void run() { 37 System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority()); 38 39 } 40 }
守护线程
线程分为用户线程和守护线程
虚拟机必须确保用户线程执行完毕
但虚拟机不用等待守护线程执行完毕
守护线程一般包括:后台记录日志,监控内存,垃圾回收等待等等
1 //测试守护线程 2 public class TestDaemon { 3 public static void main(String[] args) { 4 God god = new God(); 5 You you = new You(); 6 7 8 Thread thread = new Thread(god); 9 thread.setDaemon(true);//默认是false,正常线程都是用户线程 10 thread.start();//god线程启动 11 new Thread(you).start();//you启动 12 } 13 } 14 //GOD 15 class God implements Runnable{ 16 @Override 17 public void run() { 18 while (true){ 19 System.out.println("god bless you"); 20 } 21 } 22 } 23 24 //YOU 25 class You implements Runnable{ 26 @Override 27 public void run() { 28 for (int i = 0; i < 36500; i++) { 29 System.out.println("alive"); 30 } 31 System.out.println("=====goodbye world===="); 32 } 33 }
将god线程设置为守护线程
虚拟机不必等待god线程结束
在you线程正常结束后即可结束程序
标签:myPriority,Thread,22,day,start,线程,new,public From: https://www.cnblogs.com/GUGUZIZI/p/16870415.html