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();
			}
		}

	}
}

控制台:

java多线程1:线程调用具有随机性,cpu执行哪个线程具有不确定性_第1张图片

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();

	}
}

控制台:

java多线程1:线程调用具有随机性,cpu执行哪个线程具有不确定性_第2张图片

 

你可能感兴趣的:(java多线程1:线程调用具有随机性,cpu执行哪个线程具有不确定性)