3.线程的优先级和线程调度

1.每个线程都有优先级,默认为Thread.NORM_PRIORITY为5,最小为MIN_PRIORITY为1,最大Thread.MAX_PRIORITY为10,新线程继承父线程的优先级。

2.采用分片的方式,每个线程只能在一个短暂的处理器时间分片内执行,时间分片结束的时候,即使线程没有执行完,也要将处理器让给下一个具有相同优先级的线程。

采用轮转的方式来运行时间分片。

3.一个简单的多线程例子,共有四个线程,每个线程都有一个睡眠时间,睡眠时间内则处于“睡眠“状态,当睡眠时间结束,则进入就绪状态,睡眠时间短的先执行,代码如下:

package thread;

public class PrintTest {
public static void main(String args[]){
    PrintThread thread1,thread2,thread3,thread4;
    thread1 = new PrintThread("1");
    thread2 = new PrintThread("2");
    thread3 = new PrintThread("3");
    thread4 = new PrintThread("4");
    thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();
}
}
//线程类
class PrintThread extends Thread{
    int sleepTime;
    public PrintThread(String id){
        super(id);
        sleepTime = (int)(Math.random()*5000);//Math.random()会返回0-1的随机数
        System.out.println("Name:"+getName()+"; sleep:"+sleepTime);
    }
    public void run(){
        try {
            sleep(sleepTime);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Thread:"+getName());
    }
}

输出结果:

 

posted @ 2016-12-02 14:58  笨蛋敏  阅读(332)  评论(0)    收藏  举报