A requirement in Android projects: read file contents through threads, and control the start, pause and continue of threads to control the reading of files. Record it here.
Directly in the main thread, the thread (child thread) that reads the file is controlled directly through wait, notify, and notifyAll, and an error is reported: java.lang.IllegalMonitorStateException.
Several issues to note:
Three ways to obtain control of threads:
Here we will start, pause, and continue to encapsulate the thread class, and just call the method of this instance 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(); } } /** * Pause*/ void suspend(){ suspended = true; } /** * Continue*/ synchronized void resume(){ suspended = false; notify(); } }The above is all the content of this article. I hope that the content of this article will be of some help to everyone’s study or work. I also hope to support Wulin.com more!