tomcat 中的线程实现

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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值