天天看點

java se基礎4

<b>第九章 java</b><b>多線程機制</b>

線程的基本概念

線程是一個程式内部的順序控制

線程和程序的差別:

      每個程序都有獨立的代碼和資料空間(程序上下文),程序間的切換會有較大的開銷.

線程可以看成是輕量級的程序,同一類線程共享代碼和資料空間,每個線程有獨立的運作棧和程式計數器(pc),線程切換的開銷小.

多程序:在作業系統中能同時運作多個任務(程式)

多線程:在同一應用程式中有多個順序流同時執行.

Java線程是通過Java.lang.Thread類來實作的.

VM啟動時會有一個由主方法(public static void main(){})所定義的線程.

可以通過建立Thread的執行個體來建立新的線程

每個線程都是通過某個特定Thread對象所對應的方法run()來完成其操作的,方法run()稱為線程體

線程的建立和啟動

 通過調用Thread類的start()方法來啟動一個線程

 可以有兩種方式建立新的線程:

       第一種:

 定義線程類實作runnable接口

 Thread myThread = new Thread(target)//target為runnable接口類型

 Runnable中隻有一個方法:public void run()用以定義線程運作體

 使用runnable接口可以為多個線程提供共享資料

 在實作runnable接口的類的run方法定義中可以使用Thread的靜态方法public static Thread currentThread()擷取目前線程的引用.

第二種

 可以定義一個Thread的子類并重寫其run方法如:

    Class MyThread extends Thread{

     Public void run(){}

}

然後生成該類的對象:MyThread myThread = new MyThread()

Eg:

Public class TestThread1{

 Public static void main(String args[]){

 Runner1 r=new Runner1();

 r.run();

 Thread t=new Thread(r);

 t.start();

for(int i=0;i&lt;100;i++){System.out.println(“Main Thread:------”+i);}

Class Runner1 implements Runnable{

 Public void run(){

 For(int i=0;i&lt;100;i++){System.out.println(“Runner1:”+i);}

          Eg:

          Public class TestThread1{

 r.start();

 for(int i=0;i&lt;100;i++){

 System.out.println(“Main Thread:------”+i);

Class Runner1 extends Thread{

 For(int i=0;i&lt;100;i++){

 System.out.println(“Runner1:”+i);

線程的排程和優先級

線程的狀态控制

線程狀态轉換

就緒狀态 運作狀态 阻塞狀态

IsAlive()      //判斷線程是否還活着,即線程是否還未終止

getPriority()   //獲得線程的優先級數值

setPriority()   //設定線程優先級數值

Thread.sleep() //将目前線程睡眠指定毫秒數

Join() //調用某線程的該方法,将目前線程與該線程合并,即等待該線程結束,再恢複目前線程的運作.

Yield() //讓出cpu,目前線程進入就緒隊列等待排程.

Wait() //目前線程進入對象的wait pool

Notify() //喚醒對象的wait pool 中的一個/所有等待線程

notifyAll()

sleep/join/yield方法

sleep方法

 可以調用Thread的靜态方法:

 Public static void sleep(long millis) throws InterruptedException

 使得目前線程休眠(暫時停止執行millis毫秒)

 由于是靜态方法,sleep可以由類名直接調用:Thread.sleep()

Join方法

 合并某個線程

Yield方法

 讓出cpu,給其他線程執行的機會

Import java.util.*;

Public class TestInterrupt{

 Public static void main(String[] args){

 MyThread thread=new MyThread();

 Thread.start();

 Try{Thread.sleep(10000);}

 Catch(InterruptedException e){}

 Thread.interrupt();

Class MyThread extends Thread{

 Boolean flag=true;

 While(flag){

 System.out.println(“===”+new Date()+”===”);

 Try{

 Sleep(1000);

}catch(InterruptedException e){

return;

Public class TestJoin{

 MyThread2 t1=new MyThread2(“abcde”);

 T1.start();

 T1.join();

}catch(InterruptedException e){}

For(int i=1;i&lt;=10;i++){

 System.out.println(“I am main thread”);

Class MyThread2 extends Thread{

 MyThread2(String s){

 Super(s);

Public void run(){

 For(int i=1;i&lt;=10;i++){

 System.out.println(“I am”+getName());

}catch(Interrupted Exception e){

 Return;

Public class TestYield{

Class MyThread3 extends Thread{

 MyThread3(String s){super(s);}

 For(int i=1;i&lt;=100;i++){

 System.out.println(getName()+”:”+i);

 If(i%10==0){

 Yield();

繼續閱讀