SoFunction
Updated on 2025-03-08

Introduction to Java concurrent programs

Today I looked at the Java concurrent program, wrote a write-introduction program, and set the priority of the thread.

class Elem implements Runnable{
  public static int id = 0;
  private int cutDown = 5;
  private int priority;
  
  public void setPriority(int priority){
     = priority;
  }
  
  public int getPriority(){
    return ;
  }
  public void run(){
    ().setPriority(priority);
    int threadId = id++;
    while(cutDown-- > 0){
      double d = 1.2;
      while(d < 10000)
        d = d + ( + )/d;
      ("#" + 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 )
        (Thread.MAX_PRIORITY);
      else
        (Thread.MIN_PRIORITY);
      Thread t = new Thread(e);
      ();
    }
  }
}

Since the machine is very powerful, I didn't see the concurrency effect at first. I felt that it was executed in order, so I added floating point calculations in the middle to delay the time.

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

import .*;
class Elem implements Runnable{
  public static int id = 0;
  private int cutDown = 5;
  private int priority;
  
  public void setPriority(int priority){
     = priority;
  }
  
  public int getPriority(){
    return ;
  }
  public void run(){
    ().setPriority(priority);
    int threadId = id++;
    while(cutDown-- > 0){
      double d = 1.2;
      while(d < 10000)
        d = d + ( + )/d;
      ("#" + 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 )
//        (Thread.MAX_PRIORITY);
//      else
//        (Thread.MIN_PRIORITY);
//      Thread t = new Thread(e);
//      ();
//    }
    ExecutorService exec = ();
    for(int i = 0; i < 10; i++){
      Elem e = new Elem();
      if(i == 0 )
        (Thread.MAX_PRIORITY);
      else
        (Thread.MIN_PRIORITY);
      (e);
    }
    ();
  }
}