博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java 线程的开始、暂停、继续
阅读量:7202 次
发布时间:2019-06-29

本文共 1956 字,大约阅读时间需要 6 分钟。

  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();         }    }

 

如果此文对您有帮助,微信打赏我一下吧~

转载地址:http://trwum.baihongyu.com/

你可能感兴趣的文章
linux下的进程管理
查看>>
php图像处理类,上传,压缩,添加文字、图片水印
查看>>
Oracle一些demo级function
查看>>
bootstrap datepicker 日历插件
查看>>
OpenService 失败5:拒绝访问
查看>>
查看硬件信息几种方法
查看>>
Hibernate的抓取策略
查看>>
如何备考美国项目管理协会的PMP认证考试
查看>>
Spring动态创建数据源,再动态切换
查看>>
版本号转换
查看>>
我的友情链接
查看>>
IT公司软件工程师薪水排名
查看>>
获得及操作基类的方法
查看>>
Mysql安装说明
查看>>
互联网公司如何做危机公关
查看>>
学生信息管理系统架构设计
查看>>
Spring Boot(2):SpringBootApplication注解
查看>>
我的友情链接
查看>>
Apache如何每天生成独立日志文件(access_log和error_log)
查看>>
用命令行netsh修改windows的ip、网关、dns
查看>>