Details the start pause and continue of the java thread

  • 2020-05-27 05:27:07
  • OfStack

One of the requirements in the Android project is that the contents of a file are read by a thread, and that the thread can be started, paused, and continued to read the file. Record it here.

Directly in the main thread, wait, notify and notifyAll are used to control the thread (child thread) reading the file. Error: java.lang.IllegalMonitorStateException.

A few questions to pay attention to:

At any given moment, control of the object (monitor) can only be owned by one thread. Whether the wait, notify, or notifyAll methods of the executing object, you must ensure that the currently running thread takes control of the object (monitor). If you execute the above three methods of the object in a thread that has no control over it, you will get an java.lang.IllegalMonitorStateException error. JVM is multithreaded, and by default there is no guarantee that runtime threads will be sequential.

3 ways a thread can gain control:

Executes one of the synchronized instance methods of the object. Execute the synchronized static method of the corresponding class of the object. Performs a synchronization block with a synchronization lock on the object.

Here, start, pause, and continue are wrapped in a thread class and the methods of the instance are called directly.


public class ReadThread implements Runnable{
  public Thread t;
  private String threadName;
  boolean suspended=false;
  public ReadThread(String threadName){
   this.threadName=threadName;
   System.out.println("Creating " + threadName );
  }
  public void run() {
   for(int i = 10; i > 0; i--) {
   System.out.println("Thread: " + threadName + ", " + i);
   // Let the thread sleep for a while.
   try {
    Thread.sleep(300);
    synchronized(this) {
     while(suspended) {
      wait();
     }
    }
   } catch (InterruptedException e) {
    System.out.println("Thread " + threadName + " interrupted.");
    e.printStackTrace();
   }
   System.out.println("Thread " + threadName + " exiting.");
   }
  }
  /**
   *  start 
   */
  public void start(){
   System.out.println("Starting " + threadName );
   if(t==null){
    t=new Thread(this, threadName);
    t.start();
   }
  }
  /**
   *  suspended 
   */
   void suspend(){
   suspended = true;
  }
   /**
   *  Continue to 
   */
   synchronized void resume(){
    suspended = false;
    notify();
   }
 }

Related articles: