国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java并發程序入門介紹

2019-11-26 15:14:47
字體:
來源:轉載
供稿:網友

今天看了看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();  }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 昔阳县| 图们市| 泾川县| 芜湖市| 正镶白旗| 色达县| 日喀则市| 兰考县| 万全县| 监利县| 永定县| 深泽县| 尉氏县| 碌曲县| 金昌市| 垦利县| 浠水县| 明水县| 灵石县| 连平县| 军事| 宜都市| 遂宁市| 永康市| 静宁县| 汾西县| 安陆市| 从化市| 唐海县| 若羌县| 乌鲁木齐市| 阳曲县| 确山县| 永丰县| 客服| 炉霍县| 双牌县| 孝感市| 凉山| 武强县| 军事|