欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java并发程序入门介绍

程序员文章站 2024-03-03 23:10:34
今天看了看java并发程序,写一写入门程序,并设置了线程的优先级。 class elem implements runnable{ public stati...

今天看了看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();
  }
}