1、 对于线程的使用注意
a) 设置名称(能在线程创建后对线程很方便的进行debug)
b) 响应中断
c) 使用ThreadLocal
2、 Executor:ExecutorService和Future
3、 阻塞队列:put和take、offer和 poll、drainTo
4、 线程的协助手段:lock condition wait notify notifyAll
5 Lock-free:atomic , concurrentMap.putlfAbsent , CopyOnWriteArrayList
6、 关于锁的使用经验介绍
7、 并发流程控制手段:CountDownlatch、Barrier
8、 定时器:ScheduleExecutorService、大规模定时器TimerWheel
1.a启动线程要设置名字:
package cn.upcif.test;
/**
* 给线程设置名字
* @author Amy
*
*/
public class MyThread1 {
public static void main(String[] args) {
//方法一
Thread myThread = new Thread("baobao1"){
public void run(){
System.out.println("线程宝宝1");
}
};
myThread.start();
MyThread mt = new MyThread();
mt.start();
//方法三
Thread thread = new Thread(){
public void run(){
System.out.println("线程宝宝3");
}
};
thread.setName("线程宝宝3");
thread.start();
//方法四
Thread thread1 = new Thread(task);//传入任务
//ps:我并不知道这个task要写些什么东西,待办
thread1.setName("线程宝宝4");
thread1.start();
//方法5
Thread thread2 = new Thread(task,"线程宝宝5");//传入任务
thread2.start();
}
/*之前犯了一个问题就是,本来单独是方法的时候我是直接写的 public class然后系统报错
* No enclosing instance of type MyThread2 is accessible.
* Must qualify the allocation with an enclosing instance of type MyThread2 (e.g. x.new A() where x is an instance of MyThread2).
* 因为毕竟我new了一个实例为什么会报错呢?是因为我的主函数是静态的,而这个方法又是动态的所以就是写成public static class就好了
*/
//方法二
public static class MyThread extends Thread{
public MyThread(){
super("线程宝宝2");
}
public void run(){
System.out.println("线程宝宝2");
}
}
}
- b要响应线程中断
package cn.dayup.test;
/**
* 响应线性中断
* @author Amy
*
*/
public class MyThreadInterrupt {
//中断响应①
public static void Interrupt1(){
Thread th1 = new Thread("interrupt1"){
public void run(){
for(int i = 0; i < 10;i++){
System.out.println("123");
if(Thread.interrupted()){
System.out.println("6666");
break;
}
System.out.println("123");
}
}
};
th1.start();
}
//中断响应②
public static void Interrupt2() throws InterruptedException{
if(Thread.interrupted()){
throw new InterruptedException();
}
}
//中断响应③
public static void Interrupt3(){
Thread th3 = new Thread("interrupt3"){
public void run(){
for(;;){
try{
dosomethings...
}catch(InterruptedException e){
break;
}catch(Exception e){
//handle exception
}
}
}
};
th3.start();
}
public static void main(String[] args) throws InterruptedException {
Interrupt1();
Interrupt2();
Interrupt3();
}
}
1.c ThreadLocal等同于local variable(线程局部变量,会为每个线程提供一个变量值的副本,可以独立的改变自己的副本,不影响其他的线程)
initialValue():T
get():T
set(T value)
remove()
使用场景
1、To keep state with a thread (user-id, transaction-id, logging-id)
2、To cache objects which you need frequently
3、隐式传参
ThreadLocal一般都申明在静态变量中,为了不导致内存泄漏,就要调用它的remove方法