程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java並發法式入門引見

Java並發法式入門引見

編輯:關於JAVA

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();
  }
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved