sian邮箱,经典短笑话大全,维品会折扣购物网
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(); } }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论