標籤:多線程 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多線程