欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

线程关闭与定时任务 多线程 

程序员文章站 2022-07-12 18:21:00
...
多线程

public class ThreadImpl extends AbstractThread{
private  AtomicLong num = new AtomicLong();
final Timer timer = new Timer("CS", true); //定时任务

public static void main(String[] args) {

final ThreadImpl t1 = new ThreadImpl();
System.out.println("*");
//t1.waitForRunning(3000);  //阻塞
t1.start();
System.out.println("***");

// try {
// t1.thread.join(5000); //等待t1线程执行5秒
// } catch (Exception e) {
// e.printStackTrace();
// }
System.out.println("*****");

t1.timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
               t1.num.getAndIncrement();
               System.out.println("CS :" + new Date());
            }
        }, 1000 * 3, 1000); //延迟3秒,每隔一秒执行一次
//t1.shutdown(true);
}

public void run() {
while (!this.isStopped()) {
System.out.println(".");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("..");

if(num.get()>=5){
timer.cancel(); //取消定时任务
}
}
}

public String getServiceName() {
return ThreadImpl.class.getName();
}
}

public abstract class AbstractThread implements Runnable {
    private static final long JOIN_TIME = 90 * 1000;

    protected final Thread thread;
    protected volatile AtomicBoolean hasNotified = new AtomicBoolean(false);
    protected volatile boolean stopped = false;

    public AbstractThread() {
        this.thread = new Thread(this, this.getServiceName());
    }

    public abstract String getServiceName();

    public void start() {
        this.thread.start();
    }

    public void shutdown() {
        this.shutdown(false);
    }

    public void shutdown(final boolean interrupt) {
        this.stopped = true;
        try {
            if (interrupt) {
                this.thread.interrupt();
            }
            if (!this.thread.isDaemon()) {
                this.thread.join(this.getJointime());
            }
        } catch (InterruptedException e) {
        }
    }

    public long getJointime() {
        return JOIN_TIME;
    }

    public void stop() {
        this.stop(false);
    }

    public void stop(final boolean interrupt) {
        this.stopped = true;
        if (interrupt) {
            this.thread.interrupt();
        }
    }

    public boolean isStopped() {
        return stopped;
    }
}
相关标签: 多线程