Thread 2 (the 22nd day of learning Java) (waiting for wake-up mechanism, thread pool, Timer timer)

catalogue

I Wait for wake-up mechanism

II Thread pool

III Timer timer

I Wait for wake-up mechanism

  • Wait for wake-up mechanism

This is a collaboration mechanism between multiple threads. Just like you and your colleagues in the company, you may have competition for promotion, but more often you work together to complete certain tasks.

After a thread has performed the specified operation, it will enter the infinite wait state (ait()), call the notfiy() method to wake up other threads for execution, enter the infinite wait, wake up the waiting thread for execution, and so on If necessary, you can use notifyAll() to wake up all waiting threads.

wait/notify is a cooperative mechanism between threads.

  • Introduction to relevant methods of wake-up mechanism
    • public void wait(): let the current thread enter the waiting state. This method must be called by locking the object
    • public void notify(): wakes up the thread waiting on the current lock object
public class Test {
    public static Object obj = new Object();
    public static void main(String[] args) {
        /*
            Introduction to relevant methods of waiting for wake-up mechanism
                - public void wait() : To put the current thread into a waiting state, this method must be called on the lock object
                - public void notify() : Wake up the thread waiting on the current lock object. This method must be called on the lock object
         */


       // Thread 1: infinite wait
        new Thread(new Runnable() {
            @Override
            public void run() {
                // Task code
                synchronized (Test.obj) {
                    System.out.println("Thread 1:Ready to call wait Method enters infinite wait");
                    // Enter infinite waiting
                    try {
                        Test.obj.wait();// Release the lock and won't compete for cpu
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread 1:Awakened...");
                }
            }
        }).start();
        // Thread 2: wake up thread
        new Thread(new Runnable() {
            @Override
            public void run() {
                // Task code
                synchronized (Test.obj){
                    System.out.println("Thread 2:Ready to call notify Method wakes up the waiting thread");
                    Test.obj.notify();
                }
            }
        }).start();
    }
}

 

  • Waiting for wake-up cases

 

II Thread pool

Every time a thread is created, it must interact with the operating system, and the thread will be destroyed after executing the task. If a large number of threads are created frequently, it will certainly cause great overhead of system resources and reduce the running efficiency of the program.

The thread pool idea solves the problem of frequently creating threads. We can create some threads in advance and put them in a container. When the thread needs to execute a task, take the thread out of the container and put the thread back into the container after the task is executed.

 

  • JDK thread pool
    • java. util. The concurrent package defines classes and interfaces related to thread pools.
  • Executors class
    • Factory method for creating thread pool object. This class can be used to create thread pool object.

 

  • ExecutorService interface
    • The management interface of thread pool object, submit thread tasks, close thread pool and other functions.

 

  • Callable interface
    • The task interface executed by the thread is similar to the Runnable interface.
    • Interface method ` public V call()throw Exception`
    • Task method to be executed by thread
    • Compared with the run() method, the call() method has a return value and can obtain the result of thread execution.
  • Future interface
    • The asynchronous calculation result is the result after the thread execution is completed.
    • The interface method public V get() obtains the result of thread execution, which is to obtain the return value of call() method.

 

/**
 * JDK1.5 Thread pool juc package provided after
 * java.util.concurrent.Executors class
 * Executors Is a factory class that creates an object to create a thread pool object
 * static ExecutorService newFixedThreadPool(int nThreads)
 * Create a thread pool object. The transfer parameter is the number of threads in the thread pool, which is an unbounded queue
 * Method: ExecutorService interface, which returns the implementation class object
 * Interface represents the thread pool object
 * ExecutorService Interface method: submit the task executed by the thread
 *   submit(Runnable Interface implementation class)
 */
public class ThreadDemo {
    public static void main(String[] args) {
        //Create a thread pool object with a fixed number of 2 threads
        ExecutorService es =  Executors.newFixedThreadPool(2);
        //Submit task, submit method (Runnable interface implementation class)
        es.submit( new MyRunnable());
        es.submit( new MyRunnable());
        es.submit( new MyRunnable());
        es.shutdown();
    }
}

 

public class MyRunnable implements Runnable {
    public void run() {
        System.out.println(Thread.currentThread().getName()+ " Thread execution task");
    }
}

 

 

/**
 * java.util.concurrent.Callable<V>Interface
 *  V call() throws Exception;
 *  Exceptions can be thrown, and the method has a return value
 *  The interface can only be used in the thread pool
 *  The thread pool object submit (callable interface) submits thread tasks
 *  The return value of the method is the Future interface, which represents the return value after the thread is executed
 */
public class ThreadDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //Thread pool, submit a task, and get the return value after thread execution
        ExecutorService es =  Executors.newFixedThreadPool(2);
        //Accept the return value of the submit method
        Future<String> future =  es.submit(new MyCallable());
        //The method get() in the interface gets the return value of the thread
        String str = future.get();
        System.out.println(str);
    }
}

 

public class MyCallable implements Callable<String> {
    public String call()throws Exception{
        System.out.println("Thread on");
        return "Thread result string";
    }
}

 

  • Implement thread pool program
    • There is a thread of 1 + 2 to execute the string, and there is a thread of 1 + 2 to execute the string. Implement Callable interface and string cutting function: the code is omitted

III Timer timer

The timer in Java can run the program according to the specified time.

java.util.Timer is a tool used by threads to schedule tasks to be executed in the background thread in the future. The task can be scheduled to be executed once or repeated regularly. The timer is executed with a new thread, so that the timer will continue to work even if the main thread ends.

  • Method of Timer class
    • Construction method: no parameters.
    • Timing method: public void schedule (TimerTask task, date, firsttime, long period)
    • TimerTask is the task to be executed by the timer. It is an abstract class. We need to inherit and rewrite the method run()
    • The time when the firstTime timer starts executing
    • period interval, millisecond value
      /**
       * Timer: operate within the specified time interval
       * java.util.Timer Implement timer
       * The construction method is directly new without parameters
       * Start timer method:
       *                Timer task start time millisecond interval
       *   void schedule(TimerTask task, Date firstTime, long period)
       *   TimerTask Parameters, abstract classes, passing subclass objects, overriding run()
       */
      public class TimerDemo {
          public static void main(String[] args) {
              Timer timer = new Timer();
              //Start timer
              timer.schedule(new TimerTask(){
                  public void run(){
                      System.out.println("Timed execution");
                  }
              }, new Date(),3000);
          }
      }
      /*class MyTask extends TimerTask{
          public void run(){
              System.out.println("Scheduled execution ");
          }
      }*/
      

 

Keywords: Java

Added by luitron on Fri, 18 Feb 2022 19:08:29 +0200