今天看了Java並發程序,寫入門程序,並設定了執行緒的優先權。
class Elem implements Runnable{ public static int id = 0; private int cutDown = 5; private int priority; public void setPriority(int priority){ this.priority = priority; } public int getPrior(){oreity } public int get void run(){ Thread.currentThread().setPriority(priority); int threadId = id++; while(cutDown-- > 0){ double d = 1.2; while(d < 10000) d = d + (Math.E + Math.PI)/ d; System.out.println("#" + threadId + "(" + cutDown + ")"); } }}public class Basic { public static void main(String args[]){ for(int i = 0; i < 10; i++){ Elem e = new Elem(); if(i == 0 ) e.setPriority(Thread.MAX_PRIORITY) ; else e.setPriority(Thread.MIN_PRIORITY); Thread t = new Thread(e); t.start(); } }}
由於機器很強悍,所以先開始並沒看到並發的效果,感覺是按順序執行的,所以在中間加了浮點數的運算來延遲時間。
當然,main函數裡面可以用Executors來管理線程。
import java.util.concurrent.*;class Elem implements Runnable{ public static int id = 0; private int cutDown = 5; private int priority; public void setPriority(int priority){ .priority = priority; ){ return this.priority; } public void run(){ Thread.currentThread().setPriority(priority); int threadId = id++; while(cutDown-- > 0){ double d = 1.2; while(d < 10000) d = d + (Math.E + Math.PI)/d; System.out.println("#" + threadId + "(" + cutDown + ")"); } }}public class Basic { public static void main(String args[]){// for(int i = 0; i < 10; i++){// Elem e = new Elem();/ / if(i == 0 )// e.setPriority(Thread.MAX_PRIORITY);// else// e.setPriority(Thread.MIN_PRIORITY);// Thread t = new Thread(e);// t.start();// } ExecutorService exec = Executors.newCachedThreadPool(); for(int i = 0; i < 10 ; i++){ Elem e = new Elem(); if(i == 0 ) e.setPriority(Thread.MAX_PRIORITY); else e.setPriority(Thread.MIN_PRIORITY); exec.execute(e); } exec.shutdown(); }}