java线程开始和结束_Java线程之开始、暂停、恢复、结束

封装一个可操作性强的线程,避免重复造轮子

package com.jowney.jowney.lib;

/**

* Created by Jowney on 2018/5/11.

*/

public abstract class BaseThread implements Runnable {

private Boolean living = false;

private Boolean waiting = false;

private Thread thread;

private String name;

BaseThread(String name) {

this.name = name;

this.thread = new Thread(this, name);

}

/**

* 启动线程

*/

public void start() {

//线程一旦结束以后 不能再start必须重新创建

if (this.living) {

return;

}

this.living = true;

this.thread.start();

}

/**

* 挂起线程

*/

public void pause() {

//线程已经结束 或者 正在等待 则返回

if (!this.living || this.waiting) {

return;

}

this.waiting = true;

}

/**

* 恢复线程

*/

public void resume() {

//线程已经结束 或者 线程正在运行 则返回

if (!this.living || !this.waiting) {

return;

}

synchronized (this) {

this.waiting = false;

this.notifyAll();

}

}

/**

* 终止线程

*/

public void stop() {

if (!this.living) {

return;

}

if (this.waiting) {

resume();

this.waiting = false;

}

this.living = false;

}

@Override

public void run() {

while (this.living) {

try {

// 线程挂起和退出处理

if (this.waiting) {

synchronized (this) {

this.wait();

}

}

if (!this.living) return;

} catch (InterruptedException e) {

e.printStackTrace();

}

// Do what you want to do!

execute();

}

}

public abstract void execute();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值