package a;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Sender {
ThreadLocal<Integer> amout= new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return 100;
}
};
public void deposit(Integer a){
amout.set(amout.get()+a);
}
public int getAmout(){
return amout.get();
}
public static void main(String[] args) {
Sender A=new Sender();
Transfer a1=new Transfer(A);
Transfer a2=new Transfer(A);
FutureTask<Integer> task1=new FutureTask<Integer>(a1);
FutureTask<Integer> task2=new FutureTask<Integer>(a2);
Thread thread1=new Thread(task1);
Thread thread2=new Thread(task2);
thread1.start();
thread2.start();
int thread1Amout= 0;
int thread2Amout=0;
try {
thread1Amout = task1.get();
thread2Amout=task2.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println("金额初始化为100元");
System.out.println("Thread1存入金额为:"+(thread1Amout-100));
System.out.println("Thread2存入金额为:"+(thread2Amout-100));
System.out.println("全部金额为"+(thread1Amout+thread2Amout-100));
}
}
class Transfer implements Callable<Integer>{
private final Sender sender;
public Transfer(Sender sender){
this.sender=sender;
}
@Override
public Integer call() throws Exception {
for (int i = 0; i <5 ; i++) {
sender.deposit(10);
System.out.println(Thread.currentThread().getName()+"开始存钱余额一共为"+sender.getAmout());
}
return sender.getAmout();
}
}
打印结果:
Thread-0开始存钱余额一共为110
Thread-1开始存钱余额一共为110
Thread-0开始存钱余额一共为120
Thread-1开始存钱余额一共为120
Thread-0开始存钱余额一共为130
Thread-0开始存钱余额一共为140
Thread-0开始存钱余额一共为150
Thread-1开始存钱余额一共为130
Thread-1开始存钱余额一共为140
Thread-1开始存钱余额一共为150
金额初始化为100元
Thread1存入金额为:50
Thread2存入金额为:50
全部金额为200