zoukankan      html  css  js  c++  java
  • 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());
        }
    }

    输出结果:

  • 相关阅读:
    爬弹幕
    写了这么多行就给我30,呜呜呜
    ticket
    yield求平均数
    协程原理
    爬取一类字二类字的信息和笔顺gif图片
    关于CRF的相关阅读
    embedding size与vocabulary size之间的关系: e = v**0.25
    pandas多个值取数
    转 pandas pivot
  • 原文地址:https://www.cnblogs.com/caimuqing/p/6125800.html
Copyright © 2011-2022 走看看