1. 程式人生 > >Java多執行緒基礎之執行緒特性

Java多執行緒基礎之執行緒特性

核心知識:

① 使用多執行緒技術時,程式碼的執行結果與程式碼執行的順序或呼叫順序是無關的

public class MyThread  extends Thread{
	
	@Override
	public void run() {
		
		super.run();
		System.out.println("MyThread");
		
		
	}
public class Test {
	public static void main(String[] args) {
	
		MyThread myThread = new MyThread();
		myThread.start();
		System.out.println("執行結束");
	}
	

按照程式碼的執行順序來看,應該是執行run方法後先輸出MyThread,然結果並不是。

②執行緒具有隨機性

public class MyThread extends Thread {

	@Override
	public void run() {
		try {
			for (int i = 0; i < 10; i++) {
				int time = (int) (Math.random() * 1000);
				Thread.sleep(time);
				System.out.println("run=" + Thread.currentThread().getName());
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
public class Run {
	
	public static void main(String[] args) {

		try {
			
			
			MyThread myThread = new MyThread();
			myThread.start();

			for (int i = 0; i < 10; i++) {
				int time = (int) (Math.random() * 1000);
				Thread.sleep(time);
				System.out.println("main=" + Thread.currentThread().getName());
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

 

 

③執行緒啟動的順序與start()執行無關

 

public class MyThread extends Thread {
	
	private int i ;
	
	
	 public MyThread(int i ) {
		 super();
		 this.i = i;
	}

	@Override
	public void run() {
		System.out.println(i);
	}

}

 

public class Test {
	public static void main(String[] args) {
		MyThread myThread1 = new MyThread(1);
		MyThread myThread2 = new MyThread(2);
		MyThread myThread3 = new MyThread(3);
		MyThread myThread4 = new MyThread(4);
		MyThread myThread5 = new MyThread(5);
		MyThread myThread6 = new MyThread(6);
		
		myThread1.start();
		myThread2.start();
		myThread3.start();
		myThread4.start();
		myThread5.start();
		myThread6.start();
		

	}

}