线程的调度
在单个CPU计算机中 , 一个时刻只有一个线程在运行 , 所谓多线程的并发运行 , 其实是指从宏观上看 , 各个线程轮流获得CPU资源的使用权 , 分别执行各自的任务 .
Java虚拟机的一项任务就是负责线程的调度 , 线程调度是指按照特定机制为多个线程分配CPU的使用权.
那就来了解了解这些方法的使用 1.线程的优先级 2.线程的休眠 3.线程的强制运行 4.线程的礼让
1.线程的优先级
当多个线程在等待CPU资源的时候就, 线程会自动获得一个优先级 , 一般优先级高的线程获得CPU资源的可能性更大 , 但也不是绝对的 , 这是一个复杂的过程.
优先级用1-10表示 , 1表示优先级最低 , 10表示优先级最高 , 默认值是5 .如果使用了此外的数字 , 则是不可行的 .
1 package BackPack; 2 3 import java.util.HashMap; //导包 4 5 public class Text implements Runnable { 6 7 /** 8 * @param args 9 */ 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 13 //通过构造方法指定线程名 14 Thread th1 = new Thread(new Text() , "线程A"); 15 Thread th2 = new Thread(new Text() , "线程B"); 16 //设置线程的优先级 17 th1.setPriority(1); 18 th2.setPriority(10); 19 20 th1.start(); 21 th2.start(); 22 } 23 24 public void run(){ 25 for (int i = 0; i < 100; i++) { 26 System.out.println(Thread.currentThread().getName() + "正在执行 , 优先级是" + Thread.currentThread().getPriority()); 27 } 28 } 29 30 }
2.线程的休眠
sleep() 在睡眠的时候 会释放cpu 让给其他线程执行, 即使没有其他线程 抢占cpu 也需要等待睡眠时间到了以后才能真正的指定.
package BackPack; public class Test { public static void main(String[] args) { MyThread2 thread2 = new MyThread2(); MyThead3 thead3 = new MyThead3(); thread2.start(); thead3.start(); } } class MyThread2 extends Thread { @Override public void run() { for (int i = 0; i < 20; i++) { try { if (i > 5) { Thread.sleep(1000); // 可以让线程 睡眠 指定的毫秒数 // 在睡眠的时候 会释放cpu 让给其他线程执行 // 即使没有其他线程 抢占cpu 也需要等待睡眠时间到了以后才能真正的指定 } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "--->" + i); } } } class MyThead3 extends Thread { @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("哈哈跑了" + i + "圈"); } } }
3.线程的强制运行
join()方法在哪个线程被调用,则就插入到哪个线程前面.
package BackPack; /** * join 插队 , 合并 * * @author Daily growing * */ public class Test { public static void main(String[] args) { Son son = new Son(); son.start(); try { son.join();// 二狗想要插队 // 插队到当前线程前面 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 0; i < 100; i++) { System.out.println("主线程执行第" + i + "次"); } } } class Son extends Thread { @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("次线程执行第" + i + "次"); } } }
4.线程的礼让
yield(); 执行的时候 会 让出cpu , 但是 会立马同其他的线程抢占 cpu
package sss; public class Test { public static void main(String[] args) { MyThrad1 myThrad1 = new MyThrad1("哈哈哈"); MyThead2 myThead2 = new MyThead2(); myThrad1.start(); myThead2.start(); } } class MyThrad1 extends Thread { public MyThrad1(String name) { super(name); } @Override public void run() { for (int i = 0; i < 20; i++) { Thread.yield();// 执行的时候 会 让出cpu , 但是 会立马同其他的线程抢占 cpu System.out.println(Thread.currentThread().getName() + "跑了" + i + "圈"); } } } class MyThead2 extends Thread { @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println("嘻嘻嘻跑了" + i + "圈"); } } }

浙公网安备 33010602011771号