线程入门——不恰当的资源共享

IntGenerator不是runnable类java

 

/**
 * Created by Administrator on 2017/9/6.
 */
public abstract class IntGenerator {
    private volatile boolean canceled = false;

    public abstract int next();

    //Allow this to be canceled
    public void cancel() {
        canceled = true;
    }

    public boolean isCanceled() {
        return canceled;
    }

}

 

/**
 * Created by Administrator on 2017/9/6.
 */
public class EvenGenerator extends IntGenerator {
    private int currentEvenValue = 0;
    public int next(){
        ++currentEvenValue;//danger place
        ++currentEvenValue;
        return currentEvenValue;
    }

    public static void main(String[] args){
        EvenChecker.test(new EvenGenerator());
    }
}

 

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2017/9/6.
 */
public class EvenChecker implements Runnable {
    private IntGenerator intGenerator;
    private final int id;

    public EvenChecker(IntGenerator g, int ident) {
        this.intGenerator = g;
        this.id = ident;
    }

    public void run() {
        while (!intGenerator.isCanceled()) {
            int val = intGenerator.next();
            if (val % 2 != 0) {
                System.out.println(val + "not even");
                intGenerator.cancel();
            }
        }
    }

    public static void test(IntGenerator gp, int count) {
        System.out.println("Press crl+c to exit");
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < count; i++) {
            executorService.execute(new EvenChecker(gp, i));
        }
        executorService.shutdown();
    }

    public static void test(IntGenerator gp) {
        test(gp, 10);
    }
}

正常状况下,若是标注//danger place的地方不出问题,该程序会一直运行下去。ide

但在实际运行中,一个任务有可能在另外一个任务执行第一个对currentEvenValue的递增操做以后,可是没有执行第二个操做以前,调用next()方法,致使next()调用结果为奇数。为证实有可能发生,EvenCheck.test建立了一组EvenChecker对象,并测试检查每一个数值是否都为偶数,若是不是,就会报告错误,而程序也会关闭。测试

相关文章
相关标签/搜索