class ThreadRun implements Runnable {
NumberValue number;
int value;
ThreadRun(NumberValue number,int value) {
this.number=number;
this.value = value;
Thread t = new Thread(this);
t.start();
}
@Override
public void run() {
// number = number.getThreadLocal();
number.setId(number.getId()+value);
System.out.println(number.getId());
}
}
public class ThreadTest {
public static void main(String[] args) {
NumberValue number = new NumberValue(1);
new ThreadRun(number, 1);
new ThreadRun(number, 2);
}
}
class NumberValue {
int id;
ThreadLocal<NumberValue> threadLocal = new ThreadLocal<NumberValue>() {
@Override
protected NumberValue initialValue() {
return new NumberValue(id);
}
};
NumberValue(int id) {
this.id = id;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
public NumberValue getThreadLocal() {
return threadLocal.get();
}
}
No comments:
Post a Comment