看张老师的视频课程的观后感:
看到张老师讲ThreadLocal时给我们提了个问题,怎么捕足线程结束的消息,然后及时清除,(注意,ThreadLocal 能自动清除结束的线程,目前我们只是谈得一种思想,怎么知道线程已结束)API没有提供类似的方法,那我们怎么解决呢,我发表一下我的愚见:
对于一个线程来说,run方法完事了,这个进程也就算完事了,所以我们在run方法完事时处理一下就行,下面是我基于张孝祥老师改编的:
class Thread2 extends Thread {
private ThreadLocal local;
public Thread2(ThreadLocal local) {
this.local=local;
}
public void run(){
super.run();
myRun();
if(local!=null)local.remove();//就是在run方法结束时调用remove()方法,及时清除
System.out.println(Thread.currentThread().getName()+" 已结束");
}
public void myRun(){
}//自己覆盖的方法
}
用上面对象,只须覆盖myRun()程序在结束时就能自动清除了,用RUNABLE时的就不写了,下面的测试
public class MyThreadTest {
static ThreadLocal loc=new ThreadLocal();
public MyThreadTest() {
for(int i=0;i<2;i++){
new Thread2(loc){
public void mYrun(){
int date=new Random().nextInt();
System.out.println(Thread.currentThread().getName()+" has put "+date);
loc.set(date);
new A().get();
new B().get();
}
}.start();
}
}
public static void main(String[] args) {
MyThreadTest mythreadtest = new MyThreadTest();
}
class A{
public void get(){
System.out.println("A from"+Thread.currentThread().getName()+" " +MyThreadTest.loc.get());
}
}
class B{
public void get(){
System.out.println("A from"+Thread.currentThread().getName()+" " +MyThreadTest.loc.get());
}
}
}
今天就写道这里