java多線程 基礎(二) Thread Runnable
來源:互聯網
上載者:User
[線程的並發與並行]
在單CPU系統中,系統調度在某一時刻只能讓一個線程運行,雖然這種調試機制有多種形式(大多數是時間片輪巡為主),但無論如何,要通過不斷切換需要啟動並執行線程讓其啟動並執行方式就叫並發(concurrent)。而在多CPU系統中,可以讓兩個以上的線程同時運行,這種可以同時讓兩個以上線程同時啟動並執行方式叫做並行(parallel)。
[ 並發:(1)在CUP閒置時候可以對某一個線程時行調度,運行
(2)當某一線程運行一部分後需要另一線程產生的結果,才能運行下去。
並行: 在多cup的情況下可以同時運行兩個以上的線程的進候屬於並行, 這些線程這間是獨立的,並沒有太多 的聯絡
]
[JAVA線程對象]
在JAVA中,要開始一個線程,有兩種方式。
一 是直接調用Thread執行個體的start()方法
二 將Runable執行個體傳給一個Thread執行個體然後調用它的start()方法。
產生一個線程的執行個體,並不代表啟動了線程。而啟動線程是說在某個線程對象上啟動了該執行個體對應的線程,當該線程結束後,並不會就立即消失。
樣本一 :
public class SongThread extends Thread{
private int x=0;
public void run(){
for(int i=0;i<100;i++){
try {
Thread.sleep(1);
System.out.println(x++);
} catch (InterruptedException e) {
System.out.println(x++);
}
}
}
//測試1:單獨調動已經執行個體化的線程類。線程類SongThread並不是main中的主線程。所以會先運行system.out.println();
public static void main(String[] args){
SongThread songthread=new SongThread();
songthread.start();
System.out.println("songqiu");
}
//測試2:把SongThread類加入main主線程
// public static void main(String[] args){
// System.out.println("songqiu");
// SongThread songthread=new SongThread();
// songthread.start();
// try {
// songthread.join();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println("songqiu");
// }
//測試3:當線程類SongThread調用過一次start()方法後,然後在去調用一次start(),這個時候去發生異常
//異常產生的原因是:繼承Thread抽象類別的類,啟動線程類只能產生一個線程,當這個線程類調用start()方法後,會自動結束線程的生命週期
// public static void main(String[] args){
// SongThread songthread =new SongThread();
//
// System.out.println("第一次調用線程songthread : 開始......");
// songthread.start();
// try {
// songthread.join();
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println("第一次調用線程songthread結束。");
// System.out.println("=================");
//
// System.out.println("第二次調用線程songthread : 開始......");
// try{
// songthread.start();
// System.out.println("第二次調用線程songthread結束。");
// }catch(IllegalThreadStateException e){
// System.out.println("第二次調用線程時發生異常!");
// }
// }
}
樣本二:
public class SongRunnable implements Runnable{
private int x=0;
public void run() {
for(int i=0;i<100;i++){
try {
Thread.sleep(1);
System.out.println(x++);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//測試1:此類繼承了介面Runnable,然後去實現run()方法,但此類要產生線程的話必須用Thread抽象類別去封裝
//此方法任可以加入main主線程
public static void main(String[] args){
new Thread(new SongRunnable()).start();
}
//測試2:產生多個線程,線程可以利用存貯地區裡的變最
// public static void main(String[] args){
// SongThread songthread=new SongThread();
//
// for(int i=0;i<2;i++){
//
// System.out.println("第"+(i+1)+"調用線程,開始...");
// Thread threadRunnable =new Thread(songthread);
// threadRunnable.start();
// try {
// threadRunnable.join();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// System.out.println("第"+(i+1)+"調用線程結束。");
// System.out.println("==============================");
// }
// }
}