定义一个单例model;
package com.shirt.test;
/**
* @author xiaxt
* @date 2018/12/21.
*/
public class RunModel {
private boolean isRunning; //执行状态
private String message; //执行信息
private Object data; //执行数据
private RunModel(boolean b) {
this.isRunning = b;
}
private RunModel setIsRunning(boolean b){
this.isRunning = b;
return this;
}
private RunModel setMessage(String msg){
this.message = msg;
return this;
}
private RunModel setData(Object data){
this.data = data;
return this;
}
private static class Running {
private static RunModel instance = new RunModel(false);
}
/**
* 线程运行结束
* @return
*/
public static RunModel runOver(){
return getInstance().setIsRunning(false).setMessage(null).setData(null);
}
/**
* 线程开始运行
* @return
*/
public static RunModel running(){
return getInstance().setIsRunning(true);
}
public static RunModel running(String msg){
return getInstance().setIsRunning(true).setMessage(msg);
}
public static RunModel running(String msg, Object o){
return getInstance().setIsRunning(true).setMessage(msg).setData(o);
}
/**
* 获取定时任务执行状态isRunning
* @return
*/
public static boolean isRunning() {
return getInstance().isRunning;
}
/**
* 获取定时任务执行信息message
* @return
*/
public static String getMessage() {
return getInstance().message;
}
/**
* 获取定时任务执行数据data
* @return
*/
public static Object getData() {
return getInstance().data;
}
/**
* 获取实例化对象
* @return
*/
public static RunModel getInstance() {
return Running.instance;
}
}
main函数调用测试
package com.shirt.test;
/**
* @author xiaxt
* @date 2018/8/9.
*/
public class MainTest {
public static void main(String[] args){
new Thread(new ThreadA()).start();
new Thread(new ThreadB()).start();
new Thread(new ThreadC()).start();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class ThreadA implements Runnable{//继承Thread类
//重写run方法
public void run(){
if (RunModel.isRunning()){
System.out.println(RunModel.getMessage()+",线程A跳出!");
return;
}
RunModel.running("线程A执行中");
System.out.println("线程A开始执行");
try {
Thread.sleep(100);
System.out.println("线程A睡眠0.1秒");
} catch (InterruptedException e) {
e.printStackTrace();
}
RunModel.runOver();
System.out.println("线程A执行结束");
}
}
class ThreadB implements Runnable{//继承Thread类
//重写run方法
public void run(){
if (RunModel.isRunning()){
System.out.println(RunModel.getMessage()+",线程B跳出!");
return;
}
RunModel.running("线程B执行中");
System.out.println("线程B开始执行");
try {
Thread.sleep(100);
System.out.println("线程B睡眠0.1秒");
} catch (InterruptedException e) {
e.printStackTrace();
}
RunModel.runOver();
System.out.println("线程B执行结束");
}
}
class ThreadC implements Runnable{//继承Thread类
//重写run方法
public void run(){
if (RunModel.isRunning()){
System.out.println(RunModel.getMessage()+",线程C跳出!");
return;
}
RunModel.running("线程C执行中");
System.out.println("线程C开始执行");
try {
Thread.sleep(100);
System.out.println("线程C睡眠0.1秒");
} catch (InterruptedException e) {
e.printStackTrace();
}
RunModel.runOver();
System.out.println("线程C执行结束");
}
}