现在的位置: 首页 > 综合 > 正文

线程的调度问题

2013年08月25日 ⁄ 综合 ⁄ 共 1870字 ⁄ 字号 评论关闭

线程的调度问题一直是我比较困惑的地方。

根据书上说的,线程调度时jvm中的一部分,它决定在任意指定的时刻应该运行哪个线程,并把线程带出运行状态。线程的调度定义了java运行环境如何交换任务以及如何选择下一个即将被执行的任务。

而在对线程调度的实现时,可以通过优先级,sleep()方法,yield()方法,join()发个方法来完成。

但是线程的选择运行又不是确定的,所以通过调度只是让线程按某种方式运行,而不能彻底规定它。

下面的程序通过执行循环,记录次数来体现出线程优先级的高低,另外,本程序与CPU本身的性能还有关。

Code:
  1. /*  
  2.  * Test the problem about priority  
  3.  */  
  4.   
  5. package com.thread;   
  6.   
  7. /**  
  8.  *  
  9.  * @author Han Bin  
  10.  */  
  11. class Clicker implements Runnable{   
  12.     int click=0;   
  13.     Thread t;   
  14.     private volatile boolean running=true;//volatile 是共享变量,用于并发线程的共享   
  15.     public Clicker (int p){   
  16.         t=new Thread(this);   
  17.         t.setPriority(p);   
  18.     }   
  19.     public void run(){   
  20.         while(running){   
  21.             click++;   
  22.         }   
  23.     }   
  24.     public void stop(){   
  25.         running=false;   
  26.     }   
  27.     public void start(){   
  28.         t.start();   
  29.     }   
  30. }   
  31. public class XianCheng6 {   
  32.     public static void main(String[] args){   
  33.         Thread.currentThread().setPriority(Thread.MAX_PRIORITY);   
  34.         Clicker hi=new Clicker(Thread.NORM_PRIORITY+2);   
  35.         Clicker lo=new Clicker(Thread.NORM_PRIORITY-2);   
  36.         hi.start();   
  37.         lo.start();   
  38.         try{   
  39.             Thread.sleep(10000);   
  40.         }catch(Exception e){   
  41.             System.out.println("主线程异常");   
  42.         }   
  43.         lo.stop();   
  44.         hi.stop();   
  45.         try{   
  46.             hi.t.join();   
  47.             lo.t.join();   
  48.         }catch(Exception e){   
  49.             System.out.println("异常");   
  50.         }   
  51.         System.out.println("低优先级线程:"+lo.click);   
  52.         System.out.println("高优先级线程:"+hi.click);   
  53.     }   
  54. }   

 

 

理论上,优先级高的线程比优先级低的线程将获得更多的CPU时间,虽然在实际中并不是只有这么一个原因影响着线程获得CPU时间。但是我们一般还是对想要让它获得更多CPU时间的线程设定高一些的线程优先级别。设定线程的优先级一般用setPriority(int level)方法来实现。 level从MIN_PRIORITY一直到MAX_PRIORITY,即从1到10,默认的线程优先级为5(NORM_PRIORITY)。获得当前线程优先级一般用getPriority()方法。

另外,便是对volatile这个关键字的理解问题。对这个关键字本人不甚理解,想深入了解的朋友可以参考下下面这个网址(我就不废话了):http://www.ibm.com/developerworks/cn/java/j-jtp06197.html

抱歉!评论已关闭.