理解高并发(18).编写自己的threadlocal

来源:互联网 发布:海绵软件 编辑:程序博客网 时间:2024/06/07 03:42

李四 当前投票次数 :5
张三 当前投票次数 :4
李四 当前投票次数 :6
张三 当前投票次数 :5
李四 当前投票次数 :7
张三 当前投票次数 :6
李四 当前投票次数 :8
张三 当前投票次数 :7
李四 当前投票次数 :9
张三 当前投票次数 :8
李四 当前投票次数 :10
张三 当前投票次数 :9
李四 over
张三 当前投票次数 :10
张三 over


源码如下:
  • MyThreadLocal.java

package com.test.thread.demo12;

import java.util.HashMap;
import java.util.Map;

public abstract class MyThreadLocal<T> {
public T get(){
MyThread thread = (MyThread) Thread.currentThread();
Map<String, Object> map = thread.map;
if(map == null){
thread.map = new HashMap<String, Object>();
thread.map.put(this.toString(), initValue());
return initValue();
}
return (T)thread.map.get(this.toString());
}
public void set(T t){
MyThread thread = (MyThread) Thread.currentThread();
Map<String, Object> map = thread.map;
if(map == null){
thread.map = new HashMap<String, Object>();
}
thread.map.put(this.toString(), t);
}
public void remove(){
//MyThread thread = (MyThread) Thread.currentThread();
//thread.map.clear();
}
abstract public T initValue();
}


  • MyThread.java
package com.test.thread.demo12;

import java.util.Map;

public class MyThread extends Thread{
public Map<String, Object> map = null;
public MyThread(Runnable runnable){
super(runnable);
}
}

  • Ticket.java

package com.test.thread.demo12;
public class Ticket {
MyThreadLocal<Integer> times = new MyThreadLocal<Integer>(){
@Override
public Integer initValue() {
return 0;
}
};

public void select() {
int t = times.get();
t++;
times.set(t);
System.out.println(Thread.currentThread().getName() + " 当前投票次数 :" + times.get());
if (times.get() == 10) {
System.out.println(Thread.currentThread().getName() + " over");
times.remove();
}
}
}

  • TestClient.java
package com.test.thread.demo12;

public class TestClient {
public static void main(String[] args) {
final Ticket ticket = new Ticket();
Thread t = new MyThread(new Runnable(){
public void run(){
for(int j=0; j<10; j++){
ticket.select();
}
}
});
t.setName("张三");
Thread t2 = new MyThread(new Runnable(){
public void run(){
for(int j=0; j<10; j++){
ticket.select();
}
}
});
t2.setName("李四");
t.start();
t2.start();
}
}

原创粉丝点击