Concurrency - sleeping priority

Sleeping
A simple way to affect the behavior of your tasks is by calling sleep( ) to cease (block) the execution of that task for a given time.
If you must control the order of execution of tasks, your best bet is to use synchronization controls.
public class SleepingTask extends LiftOff{
    
public void run(){
        
try {
            
while(countDown-- > 0){
                System.out.print(status());
                
// Old-style:
                
// Thread.sleep(100);
                
// Java SE5/6-style
                TimeUnit.MICROSECONDS.sleep(100);
            }
        } 
catch (InterruptedException e) {
            
// TODO: handle exception
        }
    }
    
    
public static void main(String[] args)  {
        ExecutorService exec 
= Executors.newCachedThreadPool();
        
for(int i=0; i<5; i++)
            exec.execute(
new SleepingTask());
        exec.shutdown();
    }
}


Priority
The priority of a thread conveys the importance of a thread to the scheduler.
However, this doesn’t mean that threads with lower priority aren’t run (so you can’t get deadlocked because of priorities).
Lower-priority threads just tend to run less often.
Trying to manipulate thread priorities is usually a mistake.

Although the JDK has 10 priority levels, this doesn’t map well to many operating systems.
public class SimplePriorities implements Runnable {
    
private int countDown = 5;
    
private volatile double d; //No optimization
    private int priority;
    
public SimplePriorities(int priority){
        
this.priority = priority;
    }
    
    
public String toString(){
        
return Thread.currentThread() + "" + countDown;
    }

    @Override
    
public void run() {
        Thread.currentThread().setPriority(priority);
        
while(true){
            
// An expensive, interruptable operation
            for(int i=1; i<10000; i++){
                d 
+= (Math.PI + Math.E)/(double)i;
                
if(i%1000 == 0)
                    Thread.yield();
            }
            System.out.println(
this);
            
if(--countDown ==0)
                
return;
        }
    }

    
public static void main(String[] args) {
        ExecutorService exec 
= Executors.newCachedThreadPool();
        
for(int i=0; i<5; i++)
            exec.execute(
new SimplePriorities(Thread.MIN_PRIORITY));
        exec.execute(
new SimplePriorities(Thread.MAX_PRIORITY));
        exec.shutdown();
    }
}
















posted on 2012-11-21 10:56 盐城小土包 阅读(138) 评论(0)  编辑  收藏 所属分类: J2EE


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年12月>
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

导航

统计

常用链接

留言簿

随笔档案(14)

文章分类(18)

文章档案(18)

搜索

最新评论

阅读排行榜

评论排行榜