java cpu分配_java多线程中利用优先级来分配CPU时间的实例

public class  ServerDemo {

public static void main(String[] args){

/*优先级的设定其实并不靠谱,因为这主要依赖于操作系统,

* 即使为最大优先级也不一定会被先执行,当把下面这句设定

* 优先级的句子注释掉,会发现系统默认main线程的优先级

* 最高,反正以我之见,依赖底层实现的程序的运行结果多有

* 不确定。这可要人为地小心了,要不然干嘛还要引入同步

* 系统默认被创建的线程的优先级比创建它的线程低,设定

* 优先级一定要在run方法中使线程发生中断,这样才能让其他

* 的线程也可以获得CPU的时间!要不然就会等到执行结束

* 才会让出系统的控制权。

*/

Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

Scheduler sch = new Scheduler();

sch.setDaemon(true);

sch.start();

TestThread t1 = new TestThread("T1");

t1.start();

sch.addThread(t1); //改变线程t1的优先级

TestThread t2 = new TestThread("T2");

t2.start();

sch.addThread(t2); //改变线程t2的优先级

TestThread t3 = new TestThread("T3");

t3.start();

sch.addThread(t3); //改变线程t3的优先级

System.out.println("ok");

}

}

/*

* 这是一个调度器线程,主要作用是通过将线程添加进数组中,并依次改变它们的优先

* 级来保证它们的执行顺序的先后,可是发现在运行当中,还是没有依次执行,很疑惑

*

*/

class   Scheduler  extends Thread {

private ArrayList list = new ArrayList();

private static final  int  DEFAULT_TIME_SLICE=10;

private int slice;

private int activeIndex=0;

private Thread activeThread;

public Scheduler(){

this.slice=DEFAULT_TIME_SLICE;

this.setName("Scheduler");

}

public Scheduler(int slice){

this.slice=slice;

this.setName("Scheduler");

}

public void  addThread(Thread t){

if(t==null)

System.out.println("the Thread is null");

t.setPriority(2);

list.add(t);

}

private void schedulerSleep(){

try{

Thread.sleep(slice);

}catch(InterruptedException e){

e.printStackTrace();

}

}

@Override

public void run(){

Thread current;

this.setPriority(6);  //   make sure that the schedulerThread can execute firstly,

// so it can add the thread in list work rightly

while(true){

current = findNext();

activeThread = current; // get the thread from the list

activeIndex = list.indexOf(activeThread);  //????activeThread or current try to do it

if((current != null)&&(current.isAlive())){

activeThread.setPriority(4);

}

schedulerSleep();

if((current != null)&&(current.isAlive())){

activeThread.setPriority(2);

}

System.out.println(" end of "+Thread.currentThread().getName());

}

}

Thread findNext(){

Thread current;

int index=0;

if(activeIndex>=(list.size()-1)&&list.size()!=0)index=0;

else if(list.size()==0)return null;

//如果当前线程还处于有效状态,则继续执行当前线程

else if(activeThread != null&&activeThread.isAlive()) index = activeIndex ;

else index = activeIndex +1;

current = list.get(index); //返回指定的线程

return current;

}

}

class   TestThread extends Thread{

public TestThread(String name){

this.setName(name);

}

public void run(){

System.out.println("current name:"+

this.getName()+

" Priority:"+this.getPriority());

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值