1. 程式人生 > >java多執行緒1:執行緒呼叫具有隨機性,cpu執行哪個執行緒具有不確定性

java多執行緒1:執行緒呼叫具有隨機性,cpu執行哪個執行緒具有不確定性

java多執行緒1:

a.執行緒呼叫具有隨機性,cpu執行哪個執行緒具有不確定性

在使用多執行緒技術時,多執行緒的執行結果和多執行緒的執行順序或者呼叫順序是無關的。

執行緒是一個子任務,cup以不確定的方式,或者說是以隨機的時間來呼叫執行緒中的run方法。

 

下邊測試一波執行緒呼叫的隨機性:(呼叫方法的順序都是隨機的)

package MultiThread;

public class MainAndThread {

	public static class MyThread extends Thread {
		public void run() {
			for (int i = 0; i < 10; i++) {
				try {
					Thread.sleep(100);
					System.out.println("MyThread++++++++++++++++++" + Thread.currentThread().getName() + "" + i);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		MyThread MyThread = new MyThread();
		MyThread.setName("小熊的MyThread");
		MyThread.start();
		for (int j = 0; j < 10; j++) {
			try {
				Thread.sleep(100);
				System.out.println("main--------------------" + Thread.currentThread().getName() + "" + j);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}

控制檯:

b.執行start()方法的順序不代表執行緒啟動的順序

package MultiThread;

public class StartOrder {

	public static class MyThread extends Thread {
		int i;

		public MyThread(int i) {
			this.i = i;
		}

		public void run() {
			System.out.println("-----------" + i);
		}
	}

	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);
		MyThread myThread7 = new MyThread(7);
		MyThread myThread8 = new MyThread(8);
		MyThread myThread9 = new MyThread(9);
		MyThread myThread10 = new MyThread(10);
		MyThread myThread11 = new MyThread(11);
		myThread1.start();
		myThread2.start();
		myThread3.start();
		myThread4.start();
		myThread5.start();
		myThread6.start();
		myThread7.start();
		myThread8.start();
		myThread9.start();
		myThread10.start();
		myThread11.start();

	}
}

控制檯: