文章目录
Brian’s Rule of Synchronization——If you are writing a variable that might next be read by another thread, or reading a variable that might have last been written by another thread, you must use synchronization, and further, both the reader and the writer must synchronize using the same monitor lock.
Improperly accessing resources
import java.util.concurrent.*;
//this class is the share resources
abstract class IntGenerator{
private volatile boolean canceled =false;
public abstract int next();
// allow this to be canceled
public void canceled(){
canceled=true;}
public boolean isCanceled() {
return canceled;}
}
public class ShareResource implements Runnable{
private IntGenerator generator;
private final int id;
public ShareResource(IntGenerator g , int ident){
generator=g;
id=ident;
}
@Override
public void run() {
while (!generator.isCanceled()){
int val=generator.next();
if(val %2 !=0){
System.out.println(Thread.currentThread().getName()+" "+val +" not even");
generator.canceled();
}
}
}
public static void test(IntGenerator gp, int count){
System.out.println("Press Control-c to exit");
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i <count ; i++) {
exec.execute(new ShareResource(gp,i));
}
exec.shutdown();
}
public static void test(IntGenerator gp){
test(gp,4);
}
public static void main(String[] args) {
ShareResource.test(new EventGenerator());
}
}
class EventGenerator extends IntGenerator{
private int currentEvenValue = 0;
@Override
public int next