一:守護線程
① 什麼是守護線程?
守護線程指的是服務線程,是專門爲其它線程(用戶線程)服務的,當主線程停止了,守護線程也會被停止。
② 守護線程與用戶線程的區別?
java中有兩種線程,一個是守護線程,一個是用戶線程。守護線程指的是服務線程,比喻垃圾回收機制就是一個典型的服務線程,而用戶線程就是應用程序自定義的線程。當主線程停止了,用戶線程還會繼續運行,而守護線程主線程停止了,守護線程也就停止了。
③ 守護線程案例
/**
* 守護線程案例
*
* @Title DaemonTest01
* @Description
* @Company
* @author Zheng.Zeng
* @date 2018年6月12日 下午4:47:06
*/
public class DaemonTest01 {
public static void main (String[] args) {
DaemonThread daemonThread = new DaemonThread ();
// 設置線程爲守護線程
daemonThread.setDaemon (true);
daemonThread.start ();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep (100);
} catch (Exception e) {
}
System.out.println ("主線程");
}
System.out.println ("主線程執行完畢!");
}
}
class DaemonThread extends Thread {
@Override
public void run () {
while (true) {
try {
Thread.sleep (100);
} catch (Exception e) {
}
System.out.println ("子線程...");
}
}
}
執行結果
也有可能出現一下情況,可能有些人就會疑問這是爲什麼了。其實道理很簡單,因爲守護線程這時候已經在執行中了,正好主線程這個時候停止了。這時候這個正在執行的守護線程會執行完畢之後纔會停止守護線程。
二:join()方法
作用:讓其他線程變爲休眠狀態,直到當前線程執行完畢了釋放資源之後,其他線程才能執行
案例:
/**
* join方法案例
*
* @Title JoinTest01
* @Description
* @Company
* @author Zheng.Zeng
* @date 2018年6月12日 下午5:21:38
*/
public class JoinTest01 {
public static void main (String[] args) {
JoinThread joinThread = new JoinThread ();
Thread t01 = new Thread (joinThread);
Thread t02 = new Thread (joinThread);
t01.start ();
try {
// 讓其他線程等待t01執行完畢才執行t02
t01.join ();
} catch (InterruptedException e) {
}
t02.start ();
}
}
class JoinThread implements Runnable {
@Override
public void run () {
for (int i = 0; i < 10; i++) {
System.out.println (Thread.currentThread ().getName () + "i:" + i);
}
}
}
結果
三:優先級
在操作系統中,線程可以劃分優先級,優先級較高的線程得到CPU資源較多,也就是CPU優先執行優先級較高的線程對象中的任務(其實並不是這樣)。在Java中,線程的優先級用setPriority()方法就行,線程的優先級分爲1-10這10個等級,如果小於1或大於10,則拋出異常throw new IllegalArgumentException(),默認是5。
案例:
/**
* 優先級案例
*
* @Title PriorityTest
* @Description
* @Company
* @author Zheng.Zeng
* @date 2018年6月12日 下午5:35:23
*/
public class PriorityTest {
public static void main (String[] args) {
PriorityThread priorityThread = new PriorityThread ();
Thread thread1 = new Thread (priorityThread);
Thread thread2 = new Thread (priorityThread);
thread1.start ();
//注意設置了優先級, 不是每次都會執行。 而是CPU調度纔會分配
thread1.setPriority (10);
thread2.start ();
}
}
class PriorityThread implements Runnable {
@Override
public void run () {
for (int i = 0; i < 10; i++) {
System.out.println (Thread.currentThread ().getName () + "i:" + i);
}
}
}
結果
也有可能爲以下結果 道理請理解以上邏輯