简言Java里面的Thread

关于线程的中断机制

要使任务和线程能安全,快速,可靠地停止下来,并不是一件容易的事。Java没有提供任何机制来安全地终止线程,那么我们又该如何使用线程的停止或者中断呢?

 

 

 


public class ThreadnterruptDemo implements Runnable {
public static void main(String[] args)throws Exception{
    Thread thread=new Thread(new ThreadnterruptDemo(),"InterruptDemo Thread");
    System.out.println("Starting thread...");
    thread.start();
    Thread.sleep(3000);
    thread.interrupt();
    System.out.println("线程是否中断:"+thread.isInterrupted());
    Thread.sleep(3000);
    System.out.println("Stopping application...");
    
}
    @Override
    public void run() {
        // TODO Auto-generated method stub
        boolean stop=false;
        while(!stop) {
            System.out.println("My Thread is running...");
            long time=System.currentTimeMillis();
            while((System.currentTimeMillis()-time)<1000) {
                
            }
        }
        System.out.println("My Thread existing under request...");
    }

}

运行结果如下:
 

........................

 if(Thread.currentThread().isInterrupted()){

//需要线程本身去处理一下它的终止状态

bread;

}

代码变成了如下:

    public void run() {
        // TODO Auto-generated method stub
        boolean stop=false;
        while(!stop) {
            System.out.println("My Thread is running...");
            long time=System.currentTimeMillis();
            while((System.currentTimeMillis()-time)<1000) {
                
            }
        if(Thread.currentThread().isInterrupted()){

                //需要线程本身去处理一下它的终止状态

                break;

                }
        }
        System.out.println("My Thread existing under request...");
    }

运行结果如下:

 

 

}

 

 

线程的生命周期

 

 

 

 

 什么是守护线程

 

 

public class ThreadA extends Thread {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(long i=0;i<9999999L;i++) {
            System.out.print("后台线程A第"+i+"次执行!");
            try {
                Thread.sleep(7);
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

public class ThreadB extends Thread {
public void run() {
    for(int i=0;i<5;i++) {
        System.out.println("线程B第"+i+"次执行!");
        try {
            Thread.sleep(7);
        }catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
}


public class ThreadMain {
    public static void main(String[] args) {
Thread tA=new ThreadA();
Thread tB=new ThreadB();
tA.setDaemon(true);

tB.start();
tA.start();
Thread mainThread=Thread.currentThread();
System.out.println("线程A是不是守护线程"+tA.isDaemon());
System.out.println("线程B是不是守护线程"+tB.isDaemon());
System.out.println("线程main是不是守护线程"+mainThread.isDaemon());
}
}
运行结果如下:

 

 

 

线程组

 

 

当前线程副本:ThreadLocal

 

 


public class ThreadMain1 {
private static ThreadLocal<Integer> seqNum=new ThreadLocal<Integer>() {
    public Integer initialValue() {
        return 0;
    }
};
public ThreadLocal<Integer> getThreadLocal(){
    return seqNum;
}
public int getNextNum() {
    seqNum.set(seqNum.get()+1);
    return seqNum.get();
}
public static void main(String[] args) {
    ThreadMain1 sn=new ThreadMain1();
    TestClient t1=new TestClient(sn);
    TestClient t2=new TestClient(sn);
    TestClient t3=new TestClient(sn);
    t1.start();
    t2.start();
    t3.start();
}
private static class TestClient extends Thread{
    private ThreadMain1 sn;
    public TestClient(ThreadMain1 sn) {
        this.sn=sn;
    }
    public void run() {
        for(int i=0;i<3;i++) {
            System.out.println("thread["+Thread.currentThread().getName()+"]-->sn"+sn.getNextNum()+"]");
        }
        sn.getThreadLocal().remove();
    }
}
}

 

 

 

 

 

 

 

 

 

线程异常的处理

 

 

 

 

 

下面,我们就按照这个步骤来实现一个实例。

首先是实现UncaughtExceptionHandler接口部分:

import java.lang.Thread.UncaughtExceptionHandler;

public class ExceptionHandlerThreadB implements UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        // TODO Auto-generated method stub
       System.out.printf("An exception has been captured\n");
       System.out.printf("Thread:%s\n",t.getId());
       System.out.printf("Exception:%s:%s\n", e.getClass().getName(),e.getMessage());
       System.out.printf("Stack Trace:\n");
       e.printStackTrace(System.out);
       System.out.printf("Thread status:%s\n",t.getState());
    }

}

public class ThreadB1 implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        int number0=Integer.parseInt("TTT");
    }

}

 public class ThreadMain2 {
public static void main(String[] args) {
    ThreadB1 task=new ThreadB1();
    Thread thread=new Thread(task);
    thread.setUncaughtExceptionHandler(new ExceptionHandlerThreadB());
    thread.start();
}
}

运行结果如下:

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值