java线程调度 |
您所在的位置:网站首页 › 可以使用java的线程优先级来实现业务的优先级调度 › java线程调度 |
线程调度分为两种形式 1 分时调度模型: 所有线程轮流获得CPU使用权,平均分配每一个线程的CPU时间片 2 抢占式调度模型: 优先让优先级更高的线程使用CPU,如果线程优先级相同 那机会随机分配优先级 给优先级高的线程更多一些的时间片 而java的分配模式 是抢占式的CPU分配规则 Thread类中 有获取和设置线程的优先级方式 下面我们用代码演示一下 我们先新建一个包 包下新建两个类 customException 线程类 参考代码如下 public class customException extends Thread { public String name; public customException(){ } public void run(){ for(int i = 0;i public static void main(String args[]) { customException com1 = new customException(); customException com2 = new customException(); customException com3 = new customException(); com1.setName("地铁"); com2.setName("飞机"); com3.setName("轮行"); com1.start(); com2.start(); com3.start(); } }这里 我们customException类中 继承了线程Thread类 并编写了run方法 是一个循环语句 然后测试类 通过customException继承的Thread类 给三个线程定义名称 然后开启了三个线程 我们运行代码如下 但其实 显然是 飞机最快 地铁勉强 轮行在大多路程中 会慢一些 那么 他们的CPU分配 应该是 飞机>地铁>轮行 然后我们注释掉线程启动的代码 然后用getPriority输出一下线程的优先级 然后编写customException类代码如下 public class customException extends Thread { public String name; public customException(){ } public void run(){ for(int i = 0;i public static void main(String args[]) { customException com1 = new customException(); customException com2 = new customException(); customException com3 = new customException(); com1.setName("地铁"); com2.setName("飞机"); com3.setName("轮渡"); com1.setPriority(5); com2.setPriority(10); com3.setPriority(1); com1.start(); com2.start(); com3.start(); } }此时 我们通过 setPriority 设置 com1 : 地铁 优先级 5 com2 : 飞机 优先级 10 com3 : 轮渡 1 我们运行代码 还有就是 setPriority 有最大最小限制 不许是 1-10之间 否则就会抛出异常 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |