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

本文通过一个简单的投票程序示例介绍了如何使用线程局部变量来为不同的线程维护独立的状态信息。两个线程(张三和李四)分别进行投票操作,各自维护自己的投票计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


李四 当前投票次数 :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();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值