gpt4 book ai didi

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

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 28 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章详解java线程的开始、暂停、继续由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

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

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

需要注意的几个问题:

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

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

  1. 执行对象的某个同步实例方法。
  2. 执行对象对应类的同步静态方法。
  3. 执行对该对象加同步锁的同步块。

这里将开始、暂停、继续封装在线程类中,直接调用该实例的方法就行.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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();
    }
  }

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

原文链接:http://www.cnblogs.com/Joanna-Yan/p/5142348.html 。

最后此篇关于详解java线程的开始、暂停、继续的文章就讲到这里了,如果你想了解更多关于详解java线程的开始、暂停、继续的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com