1. 程式人生 > >初探Java多線程

初探Java多線程

public @override 輸出 執行 bsp 輸出結果 getname row runnable

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

一、 使用多線程

1、 繼承Thread類

package com.ztz.myThread;

public class MyThread extends Thread{
	@Override
	public 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{
	@Override
	public 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());
	}
	@Override
	public 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{
	@Override
	public 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多線程