当前位置: 移动技术网 > IT编程>开发语言>Java > 详解java线程的开始、暂停、继续

详解java线程的开始、暂停、继续

2019年07月22日  | 移动技术网IT编程  | 我要评论

sian邮箱,经典短笑话大全,维品会折扣购物网

android项目中的一个需求:通过线程读取文件内容,并且可以控制线程的开始、暂停、继续,来控制读文件。在此记录下。

直接在主线程中,通过wait、notify、notifyall去控制读文件的线程(子线程),报错:java.lang.illegalmonitorstateexception。

需要注意的几个问题:

  1. 任何一个时刻,对象的控制权(monitor)只能被一个线程拥有。
  2. 无论是执行对象的wait、notify还是notifyall方法,必须保证当前运行的线程取得了该对象的控制权(monitor)。
  3. 如果在没有控制权的线程里执行对象的以上三种方法,就会报错java.lang.illegalmonitorstateexception。
  4. jvm基于多线程,默认情况下不能保证运行时线程的时序性。

线程取得控制权的3种方法:

  1. 执行对象的某个同步实例方法。
  2. 执行对象对应类的同步静态方法。
  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();
   }
 }

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网