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();
}
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!