java程式設計筆記21 執行緒

2021-09-06 02:42:57 字數 3709 閱讀 5077

1,兩種方法來建立執行緒:

1)繼承thread類實現run方法:

public class hello1 extends thread

public void run() }

}

2)實現runnable介面,實現run方法:

public class hello2 implements runnable

public void run()

}

推薦第二種方法;

2,產生thread物件和啟動執行緒

public class thread***ample1

}

3,停止執行緒執行

下面的run方法可以讓執行緒一直執行:

public class hello3 implements runnable

public void run() }

}

加乙個迴圈條件來達到停止現成的效果:

public class hello4 implements runnable

public void run() }

public void stop()//控制條件

}

當乙個執行緒物件進入死亡狀態後,就沒有任何方法可以回到其他狀態。

4,暫停執行緒執行

sleep方法:

yield方法

join方法,

來看join的乙個例子:

motherthread:
package ch22;

public class motherthread implements runnable

catch (interruptedexception ie)

system.out.println("媽媽開始煮飯");

system.out.println("媽媽煮好飯了");

}}

sonthread:

package ch22;

public class sonthread implements runnable

} catch (interruptedexception ie)

system.out.println("\n兒子買公尺酒回來了");

} }

cooking:

package ch22;

public class cooking

}

執行結果:

5,資料同步處理

現在我們有這樣乙個執行緒:

package ch22;

public class sharedata implements runnable

}}

現在我們來產生兩個sharedata物件,並給兩個thread執行:

package ch22;

public class thread***ample2

}

其結果如圖:

可以看到,兩個thread物件在互動執行,thread 0和thread 1分別從0按順序到10.

這是因為兩個thread共用了程式**但是沒有共用資料,下面我們來看程式**和資料都共用的效果:

package ch22;

public class thread***ample3

}

結果並不是你所想象的從0到10,而是:

這是為什麼呢????

這是因為執行緒被分割執行了,具體分析略。

6,synchronized實現執行緒同步

synchronized(要取得鎖的物件)

要鎖定的**

實現了兩個執行緒對同乙個物件操作的同步

7,等待wait與通報notify

生產者和消費者的例子:

package ch22;

public class storage

//類裡的方法實現了鎖,則呼叫這個方法必須取得這個類的物件的鎖

public synchronized void adddata(string n)

catch (interruptedexception e)

} this.notify();//通知消費者可以消費了

count++;

system.out.println(n+" make data count: "+count); }

public synchronized void deldata(string n)

catch (interruptedexception e)

} this.notify();

system.out.println(n+" use data count: "+count);

count--;

} }

package ch22;

public class producer extends thread

public void run()

catch (interruptedexception e)

} }}

package ch22;

public class consumer extends thread

public void run()

catch (interruptedexception e)

} }}

package ch22;

public class thread***ample5

}

producer1 make data count: 3

consumer1 use data count: 3

consumer1 use data count: 2

producer1 make data count: 2

consumer1 use data count: 2

producer1 make data count: 2

Java基礎筆記21

21.01 io流 字元流filereader 2.filereader,filewriter filereader fr new filereader aaa.txt 建立輸入流物件,關聯aaa.txt int ch while ch fr.read 1 fr.close 關流 複製 21.02 ...

《Java 執行緒程式設計》學習筆記6

thread.max priority 10 thread.min priority 1 thread.norm priority 5 何時 setpriority 失效 執行緒有如下6種狀態 執行緒規劃器控制哪乙個準備執行的執行緒實際執行於處理器上。任何時候,只有乙個執行緒實際處於執行狀態。所有其...

Java執行緒程式設計題

題目描述 編寫10個執行緒,第乙個執行緒從1加到10,第二個執行緒從11加到20.第十個執行緒從91加到100,最後再把10個執行緒結果相加。package thread test class thread test extends thread public static synchronized...