Android項目中的一個需求:通過線程讀取文件內容,并且可以控制線程的開始、暫停、繼續,來控制讀文件。在此記錄下。
直接在主線程中,通過wait、notify、notifyAll去控制讀文件的線程(子線程),報錯:java.lang.IllegalMonitorStateException。
需要注意的幾個問題:
線程取得控制權的3種方法:
這里將開始、暫停、繼續封裝在線程類中,直接調用該實例的方法就行。
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.");   }  }  /**   * 開始   */  public void start(){   System.out.println("Starting " + threadName );   if(t==null){    t=new Thread(this, threadName);    t.start();   }  }  /**   * 暫停   */   void suspend(){   suspended = true;  }   /**   * 繼續   */   synchronized void resume(){    suspended = false;    notify();   } }以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網!
新聞熱點
疑難解答