package com.ifeng.learn.lang;
/**
* tomcat 中线程实现一般都以一个类继承 Runnable
* 在类中 定义一个 Thread thread
* thread = new Thread(this);
* thread.start();
*
*
* 线程的结束以 stopped = true;
* thread.intrruped() //向线程发中断,防止线程阻塞下无法停止
* thread.join() //主线程等待此线程中结束后才执行
*
* @author Administrator
*
*/
public class AppLoader implements Runnable {
private Thread thread;
private boolean deamon;
private String threadName;
private volatile boolean stopped = false;
public AppLoader(String threadName,boolean deamon){
this.threadName = threadName;
this.deamon = deamon;
}
@Override
public void run() {
while(!stopped){
threadSleep(5000);
System.out.println(Thread.currentThread().getName()+"hello world");
}
}
private void threadSleep(int i){
try{
Thread.sleep(i);
}catch(InterruptedException e){
;
}
}
public void start(){
thread = new Thread(this,threadName);
thread.setDaemon(deamon);
thread.start();
}
public void stop(){
if(thread == null)
return ;
stopped = true;
thread.interrupt(); //防止睡眠
try{
thread.join(); //主线程等待当前线程结束
}catch(InterruptedException e){
;
}
thread = null;
}
public static void main (String args[]){
AppLoader appLoader = new AppLoader("appLoader", true);
appLoader.start();
System.out.println("1s after stop");
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("stop the thread");
appLoader.stop();
}
}
tomcat 中的线程实现
最新推荐文章于 2022-07-05 19:17:25 发布