Introduction to Java concurrent programs

  • 2020-04-01 03:47:41
  • OfStack

Today I took a look at the Java concurrency program, wrote an introductory program, and set the priority of the threads.


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();
    }
  }
}

Because the machine was so powerful, it didn't see the concurrency effect at first. It felt like it was being executed in order, so floating point arithmetic was added in the middle to delay the time.

Of course, the main function can be used inside Executors to manage threads.


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();
  }
}

Related articles: