今天看了看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 getPriority(){ 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(); } }}
由于機器很強悍,所以先開始并沒看到并發的效果,感覺是按順序執行的,所以在中間加了浮點數的運算來延遲時間。
當然,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){ this.priority = priority; } public int getPriority(){ 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(); }}
新聞熱點
疑難解答