標籤:nts open try logs tar print 好的 優先順序 style
一.線程與進程
1.線程:程式中單獨順序的控制流程。
線程本身依靠程式進行運行。
線程是程式中的順序控制流程,只能使用分配給程式的資源和環境。
2.進程:執行中的程式。
一個進程中可以包含一個或多個線程。
一個進程中至少要包含一個線程。
3.單線程:程式中只存在一個線程,實際上主方法就是一個主線程。
4.多線程:多線程是在一個程式中執行多個任務,並發執行,搶先調度。
多線程的目的是更好的使用CPU資源。
二.線程的常用方法
1.取得線程名稱:getName
2.取得當前線程:currentThread
3.判斷線程是否啟動:isAlive
4.線程的強行運行:join
5.線程的休眠:sleep
6.線程的禮讓:yield
三.線程的優先順序
1 package com.example; 2 class MyThread implements Runnable{ 3 public void run() { 4 for (int i = 0 ; i < 5; i ++){ 5 try { 6 Thread.sleep(1000); 7 System.out.println(Thread.currentThread().getName()+":"+i); 8 } catch (InterruptedException e) { 9 e.printStackTrace();10 }11 12 }13 }14 }15 public class MyClass {16 public static void main(String []args){17 Thread t6 = new Thread(new MyThread(),"a" );18 Thread t7 = new Thread(new MyThread(),"b" );19 Thread t8 = new Thread(new MyThread(),"c" );20 t6.setPriority(Thread.MIN_PRIORITY);21 t7.setPriority(Thread.NORM_PRIORITY);22 t8.setPriority(Thread.MAX_PRIORITY);23 t6.start();24 t7.start();25 t8.start();26 27 }28 }View Code
四.線程的同步與死結
1.同步:通過人為的控制和調度,保證共用資源的多線程訪問成為安全執行緒。(安全執行緒是指線程的調度順序不影響任何結果,這個時候使用多線程,只需要考慮系統的記憶體,CPU是否夠用即可)。
(1)同步代碼塊
synchronized(同步對象){
需要同步的代碼塊;
}
(2)同步方法
synchronized void 方法名稱(){}
2.死結:
學生找工作無經驗(高薪);
企業找職工給高薪(經驗);
四.線程的實現
1.繼承Thread類。
2.實現Runnable介面。
五.線程的狀態
1.建立
2.就緒
3.運行
4.阻塞
5.銷毀
2-Java多線程編程