package threads;
public class ResourceClass {
// num is a variable that many thread will use but keeped in ThreadLocal
// seqNum
// num_nothreadlocal is also a variable that many thread will use but it is
// ordinary.
// both of their initial value is 20
private ThreadLocal<Num> seqNum = new ThreadLocal<Num>();
private int num_nothreadlocal = 20;
// each variable has its getter and setter
public void setNum(int value) {
if (seqNum.get() == null)
seqNum.set(new Num());
seqNum.get().setValue(value);
}
public int getNum() {
if (seqNum.get() == null)
seqNum.set(new Num());
return seqNum.get().getValue().intValue();
}
public int getNum_nothreadlocal() {
return num_nothreadlocal;
}
public void setNum_nothreadlocal(int numNothreadlocal) {
num_nothreadlocal = numNothreadlocal;
}
public ThreadLocal<Num> getLoc() {
return seqNum;
}
//this should be in another class
public static void main(String[] args) {
ResourceClass shareobj = new ResourceClass();
// here we generate three threads to use the same object shareobj
ComsumerThread t1 = new ComsumerThread(shareobj);
ComsumerThread t2 = new ComsumerThread(shareobj);
ComsumerThread t3 = new ComsumerThread(shareobj);
t1.start();
t2.start();
t3.start();
}
//the thread to use some object class
private static class ComsumerThread extends Thread {
private ResourceClass sh;
public ComsumerThread(ResourceClass sh) {
this.sh = sh;
}
public void run() {
// each thread change the value of Num and num_nothreadlocal
// by increase 1
for (int i = 1; i <= 3; i++) {
int nm = sh.getNum();
nm++;
sh.setNum(nm);
// under ThreadLocal
// each thread has the copy value of num
// the num increase 1 by one time : 21, 22, 23
nm = sh.getNum_nothreadlocal();
nm++;
sh.setNum_nothreadlocal(nm);
// not predictable
System.out.println("thread[" + Thread.currentThread().getName()
+ "] sn [" + sh.getNum() + "]" + sh.getLoc().get()
+ " nothreadlocal:" + sh.getNum_nothreadlocal());
}
}
}
private class Num {
private Integer num;
public Num() {
num = 20;
}
public Integer getValue() {
return num;
}
public void setValue(Integer num) {
this.num = num;
}
}
}