線程(一)

一.問題

1.程序代碼一般都是順序執(zhí)行的,如何讓程序在運行過長中,實現(xiàn)多個代碼段的同時運行?
2.如何創(chuàng)建一個線程?創(chuàng)建線程的兩種方式分別是什么?
3.線程為什么要休眠?
4.Thread類都有哪些方法?
5.如何實現(xiàn)線程內部的數(shù)據(jù)共享?

二.目標

1.學習java中線程的使用
2.掌握線程的調度和控制方法

三.Thread 類創(chuàng)建線程

1.通過Thread類創(chuàng)建線程
Thread類
·直接繼承了Object類,并實現(xiàn)了Runnable接口。位于java.lang包中
·封裝了線程對象需要的屬性和方法
2.繼承Thread類--創(chuàng)建多線程的方法之一
·從Thread類派生一個子類,并創(chuàng)建子類的對象
·子類應該重寫Thread類的run方法,寫入需要在新線程中執(zhí)行的語句段。
·調用start方法來啟動新線程,自動進入run方法。
在新線程中完成計算
public class FactorialThread extends Thread {
    private int num;
    public  FactorialThread(int num){
        this.num=num;
    }

    @Override
    public void run() {
        int i = num;
        int result=1;
        System.out.println("new thread started");
        while (i>0){
            result = result*i;
            i=i-1;
        }
        System.out.println("the factorial of "+num+"is "+result);
        System.out.println("new thread ends");
    }
}
 public static void main(String[] args) {
        System.out.println("main thread starts");
        FactorialThread thread = new FactorialThread(10);
        thread.start();
        System.out.println("main thread ends");

    }
3.結果說明
·main 線程已經執(zhí)行完成,新線程才執(zhí)行完
·main方法調用thread.start()方法啟動新線程后并不等待run方法返回就繼續(xù)運行,線程的run方法在一邊獨自運行,不影響原來的main方法的運行
4.修改:延長主線程
·如果啟動新線程后希望主線程多持續(xù)一會在結束,可在start 語句后加上當前線程(這里當然是main)休眠1毫秒的語句:
 public static void main(String[] args) {
        System.out.println("main thread starts");
        FactorialThread thread = new FactorialThread(10);
        thread.start();
        try {
            Thread.sleep(1000);
        }catch (Exception e){
        }
        System.out.println("main thread ends");
}
5 創(chuàng)建3個新線程,每個線程睡眠(0~6秒),然后結束
public static void main(String[] args) {
      TestThread thread1 = new TestThread("thread1");
      TestThread thread2 = new TestThread("thread2");
      TestThread thread3 = new TestThread("thread3");
      System.out.println("starting threads");
      thread1.start();
      thread2.start();
      thread3.start();
      System.out.println("Threads started , main ends\n");
  }
public class TestThread extends Thread {
  private int sleepTime;

  public TestThread(String name) {
      super(name);
      sleepTime = (int)(Math.random()*6000);
  }

  @Override
  public void run() {
      try {
          System.out.println(getName()+"going to sleep for "+sleepTime);
          Thread.sleep(sleepTime);
      }catch (InterruptedException exception){

      }
      System.out.println(getName()+"finished");
  }
}
·運行結果

starting threads
Threads started , main ends

thread1going to sleep for 1809
thread2going to sleep for 1568
thread3going to sleep for 775
thread3finished
thread2finished
thread1finished

·說明
1.由于線程 休眠時間最長,所以最后結束,線程 休眠時間最短,所以最先結束
2.每次運行,都會產生不同的隨機休眠時間,所以結果都不相同

Thread類--常用API方法

名稱 技能
public Thread() 構建一個新的線程對象,默認名為Thread-n ,n是從0開始遞增的整數(shù)
public Thread (Runnable target) 構造一個新的線程對象,以一個現(xiàn)實Runnable接口的類的對象為參數(shù)。默認名為Thread-n ,n是從0開始遞增的整數(shù)
public Thread (String name) 構造一個新的線程對象,并同時制定線程名
public static Thread currentThread 返回當前正在運行的線程對象
public static void yieId() 使當前線程對象暫停,允許別的線程開始運行
public static void sleep(long millis) 使當前線程暫停運行制定毫秒數(shù),但此線程并不失去已獲得的鎖。
public void start() 啟動線程,jvm將調用此線程的run方法,結果是將同時運行兩個線程,當前線程和執(zhí)行run方法的線程
public void run() Thread 的子類應該重寫此方法,內容應為該線程應執(zhí)行的任務
public final void stop() 停止線程運行,釋放該線程占用的對象鎖
public void interrupt() 中斷此線程
public final void join() 如果此前啟動了線程A,調用join方法將等待線程A死亡才能繼續(xù)執(zhí)行當前線程
public final void join(long millis) 如果此前啟動了線程A,調用join方法將等待指定毫秒數(shù)或者線程A死亡才能繼續(xù)執(zhí)行當前線程
public final void setPriority(int newPriority) 設置線程優(yōu)先級
pubic final void setDaemon(Booleanon) 設置是否為后臺線程,如果當前運行線程均為后臺線程則jvm停止運行。這個方法必須在start()方法前使用
public final void checkAccess() 判斷當前線程是否有權力修改調用此方法的線程
public void setName(String name) 更改本線程的名稱為指定參數(shù)
public final boolean isAlive() 測試線程是否處于活動狀態(tài),如果線程被啟動并且沒有死亡則返回true

四、通過Runable接口構造線程

1.Runable接口
·只有一個run()方法
·Thread類實現(xiàn)了Runable接口
· 便于多個線程共享資源
· java不支持多繼承,如果已經繼承了某基類,便需要實現(xiàn)Runable接口來生成多線程
· 已實現(xiàn)Runable的對象為參數(shù)建立新的線程
· start 方法啟動線程就會運行run()方法
2.使用Runable接口實現(xiàn)上面單線程的例子
    public static void main(String[] args) {
        System.out.println("mian thread starts");
        FactorialThread thread = new FactorialThread(10);
        new Thread(thread).start();
        System.out.println("new thread started ,main thread ends");
    }
3.兩種線程構造方式的比較
· 使用runnable接口
①可以將CPU,代碼和數(shù)據(jù)分開,形成清晰的模型;還可以從其他類繼承
·直接繼承Thread類
① 編寫簡單,直接繼承,重寫run方法,不能再從其他類繼承
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容