【Java總結-線程】Java多線程的使用

來源:互聯網
上載者:User

標籤:多線程

建立線程的兩種方式繼承Thread類
  • 定義一個類繼承Thread類
  • 子類中重寫Thread類中的run方法
  • 建立Thread子類的對象,就是建立了線程對象
  • 調用線程對象的start方法,啟動線程,會自動調用run方法
public class TestThread extends Thread {    public static void main(String[] args) {        TestThread tt = new TestThread();        tt.start();    }    //重寫run方法    public void run() {        System.out.println("run");    }}
實現Runnable介面
  • 自已子類實現Runnable介面
  • 重寫介面中的run方法
  • 通過Thread含參構造器建立線程對象
  • 將Runnable介面子類的對象作為實參傳遞
  • 調用Thread類的start方法,開啟線程
public class TestThread {    public static void main(String[] args) {        T t = new T();        Thread tt = new Thread(t);        tt.start();    }}class T implements Runnable {    @Override    public void run() {        System.out.println("run");    }}

應該多使用Runnable介面實現多線程,可以實現多繼承

String getName();返回當前線程void setName(String name);//設定線程名字static currentThread();//返回當前線程
setPriority(int new);//改變線程的優先順序getPriority()返回線程的優先順序
Thread.sleep(10);//讓線程睡10秒,阻塞
線程同步
synchroized(對象) {    //需要同步的代碼}
public synchroinized void show(String name) {    ...}
線程通訊
wait();//讓當前線程等待notify();//喚醒線程notifyAll();//喚醒正在排隊的所有線程

【Java總結-線程】Java多線程的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.