標籤:rac print 方法 [] package div alt 原因 stack
一、線程的基本概念:
線程是一個程式裡面不同的執行路徑。程式裡面不同的執行路徑,每一個分支都是一個線程。 進程:靜態概念。機器上的一個class檔案,機器上的一個exe檔案,這叫一個進程。機器裡面實際上啟動並執行都是線程。window等。linux等都是多進程,多線程的系統。 CPU的執行是這樣的:CPU速度比較快,一秒鐘算好幾億次,它把自己的時間分成一個一個的小時間片,這個時間片我執行你一會,再執行他一會,雖然有幾十個線程,沒關係,執行這個一會,執行那個一會,挨著排的都執行一遍,但是對我們人來說,因為它速度太快了,你看起來就好像好多線程在同時執行一樣。但實際上,在一個時間點上, 這個CPU只有一個線程在運行。如果機器是雙CPU,或者是雙核,那麼確實是多線程。 二、線程的啟動和建立: 例子1:實現Runnable介面:
package com.cy.thread;public class TestThread1 { public static void main(String[] args) { Runner1 r = new Runner1(); Thread t = new Thread(r); //啟動一個線程,線程啟動必須調用Thread類的start()方法 //start方法會通知cpu,我現在有個新線程了啊,已經準備好了,您老人家什麼時候有時間趕緊給我點時間片。 t.start(); for(int i=0; i<100; i++){ System.out.println("Main Thread:----- " + i); } }}/** * 實現了Runnable之後,jdk就知道了,這是一個線程類。 */class Runner1 implements Runnable{ @Override public void run() { for(int i=0; i<100; i++){ System.out.println("Runner1: " + i); } } }
console:
例子2:繼承Thread類:
package com.cy.thread;public class TestThread1 { public static void main(String[] args) { Runner1 r = new Runner1(); r.start(); for(int i=0; i<100; i++){ System.out.println("Main Thread:----- " + i); } }}class Runner1 extends Thread{ @Override public void run() { for(int i=0; i<100; i++){ System.out.println("Runner1: " + i); } } }
三、線程的狀態轉換: new Thread()一個線程之後,不會馬上執行而是進入就緒狀態,因為cpu很忙,可能正在執行其他程式;等到cpu有空了,cpu分配時間片執行(調度)這個Thread一會;Thread進入運行狀態;當cpu分配給這個Thread的時間片用完了,或者其他原因故障等,Thread不再執行,阻塞,再次進入就緒狀態;直到這個Thread的程式執行完畢;終止。 四、線程式控制制的基本方法:
isAlive(): 判斷線程是否還活著,即線程是否還未終止;就緒、運行、阻塞叫活著。終止了就死了。線程建立完還沒啟動那也是死的。getPriority() 獲得線程的優先順序數值;優先順序越高的線程獲得的cpu執行的時間越多。setPriority() 設定線程的優先順序數值;Thread.sleep() 將當前線程睡眠指定毫秒數。join() 合并某個線程。yield() 高風亮節,讓出cpu,讓其他的線程執行,而自己進入就緒狀態。wait() 當前線程進入對象的wait pool;notify、notifyAll() 喚醒對象的wait pool中的一個/所有等待線程。
View Code
五、sleep方法:
package com.cy.thread;import java.util.Date;public class TestInterrupt { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); try { /** * 在哪個線程裡面調用sleep方法,就讓哪個線程睡眠。 */ Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } /** * interrupt()方法:thread線程在睡眠的時候,將它打斷。 * 這裡為了例子示範,讓子線程結束。 * 但這不是讓子線程結束的最好方法。 */ thread.interrupt(); }}class MyThread extends Thread{ @Override public void run() { while(true){ System.out.println("==="+new Date()+"==="); try { sleep(1000); } catch (InterruptedException e) { return; } } }}View Code
console列印:
上面的程式提供一個結束Mythread線程的方法:
/** * 提供一個讓線程結束的方法: * thread.flag = false; run()方法就不再執行了,run方法一結束,線程就結束了。 */class MyThread2 extends Thread{ boolean flag = true; @Override public void run() { while(flag){ System.out.println("==="+new Date()+"==="); try { sleep(1000); } catch (InterruptedException e) { return; } } }}View Code
---------------
java多線程(1) 線程的基本概念