初探Java多線程

來源:互聯網
上載者:User

標籤:多線程   java   

什麼是多線程?這些話就不說了,直接看例子。

一、  使用多線程 1、  繼承Thread類

package com.ztz.myThread;public class MyThread extends Thread{@Overridepublic void run() {System.out.println("繼承Thread");}public static void main(String[] args)throws Exception {MyThread t=new MyThread();t.start();}}

2、  實現Runnable介面

package com.ztz.myThread;public class MyRunnable implements Runnable{@Overridepublic void run() {System.out.println("實現Runnable介面");}public static void main(String[] args)throws Exception {MyRunnable runnable=new MyRunnable();Thread thread=new Thread(runnable);thread.start();}}

PS:線程的啟動是start()方法,不是run()方法。繼承Thread類的方式是有局限性的,因為java是單繼承,為了改變這個局限性,我們可以實現Runnable介面來實現多線程


二、  currentThread()方法currentThread()方法可以傳回碼段正在被哪個線程調用的資訊。
package com.ztz.myThread;public class MyThread{public static void main(String[] args)throws Exception {System.out.println(Thread.currentThread().getName());}}
運行該方法,控制台輸出:main
說明:main方法被名為main線程調用。Thread.currentThread().getName()是獲得線程名
package com.ztz.myThread;public class MyThread extends Thread{public MyThread() {System.out.println("構造方法:"+Thread.currentThread().getName());}@Overridepublic void run() {System.out.println("run:"+Thread.currentThread().getName());}public static void main(String[] args)throws Exception {MyThread thread=new MyThread();thread.start();}}
運行該方法控制台輸出:構造方法:main
run:Thread-0

其實,main也就是主線程了Thread-0是子線程,如果在啟動個線程就是Thread-1了。

三、  sleep()方法方法sleep()的作用是在指定的毫秒數內讓當前正在執行的線程休眠(暫停執行),這個正在執行的線程是指this.currentThread()返回的線程。
package com.ztz.myThread;public class MyThread extends Thread{@Overridepublic void run() {try{System.out.println("run start:"+System.currentTimeMillis());Thread.sleep(2000);System.out.println("run end:"+System.currentTimeMillis());}catch(Exception e){}}public static void main(String[] args)throws Exception {MyThread thread=new MyThread();System.out.println("thread start:"+System.currentTimeMillis());thread.start();System.out.println("thread end:"+System.currentTimeMillis());}}

輸出結果:thread start:1437233204468
thread end:1437233204468
run start:1437233204468
run end:1437233206468
四、  getId()方法getId()方法的作用是取得線程的唯一標識。
package com.ztz.myThread;public class MyThread{public static void main(String[] args)throws Exception {Thread currentThread = Thread.currentThread();System.out.println(currentThread.getName()+"--->"+currentThread.getId());}}

輸出結果:main--->1



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

初探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.