日期:2014-05-20 浏览次数:20786 次
package src;
public class StackNode {
private Object value;
private StackNode next;
private final Object lock = new Object();
public StackNode() {
setValue(null);
setNext(null);
}
public StackNode(Object o) {
value = 0;
next = null;
}
public StackNode(StackNode node) {
value = node.getValue();
next = node.getNext();
}
public synchronized Object getValue() {
System.out.print(" Doing ");
System.out.println(" get ");
System.out.flush();
return value;
}
public synchronized void setValue(Object value) {
System.out.print(" making ");
System.out.println(" set ");
System.out.flush();
this.value = value;
}
public synchronized StackNode getNext() {
return next;
}
public synchronized void setNext(StackNode next) {
this.next = next;
}
}
public class TestStackNode {
private final static StackNode node = new StackNode();
@Test
public void getSetValueTest() throws InterruptedException{
node.setValue("bad");
Runnable setValue = new Runnable(){
@Override
public void run() {
node.setNext(new StackNode());
node.setValue("new");
}
};
Runnable getValue = new Runnable(){
@Override
public void run() {
Assert.assertEquals("new", node.getValue());
}
};
List<Thread> set = new ArrayList<Thread> ();
List<Thread> get = new ArrayList<Thread> ();
for (int i = 0; i < 30000; i++){
set.add( new Thread(setValue));
get.add(new Thread(getValue));
}
for (int i = 0; i < 30000; i++){
set.get(i).start();
get.get(i).start();
}
for (int i = 0; i < 30000; i++){
set.get(i).join();
get.get(i).join();
}
}