Java並發法式入門引見。本站提示廣大學習愛好者:(Java並發法式入門引見)文章只能為提供參考,不一定能成為您想要的結果。以下是Java並發法式入門引見正文
明天看了看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(); } }