在外部类中访问静态变量时静态内部线程的问题

时间:2018-06-02 05:36:57

标签: java multithreading static thread-safety

这个问题困扰了我好久,请帮帮我,谢谢。 这是我的java代码。

package com.concurrent.example;

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

/**
 * P683
 */
class CircularSet {
    private int[] array;
    private int len;
    private int index = 0;
    public CircularSet (int size) {
        array = new int[size];
        len = size;
        for (int i = 0; i < size; i++) {
            array[i] = -1;
        }
    }

    public synchronized void add(int i ) {
        array[index] = i;
        index = ++index % len;
    }

    public synchronized boolean contains(int val) {
        for (int i = 0; i < len; i++) {
            if(array[i] == val) {
                return true;
            }
        }
        return false;
    }
}

public class SerialNumberChecker {
    private static final int SIZE = 10;
    private static CircularSet serials = new CircularSet(1000);
    private static ExecutorService exec = Executors.newCachedThreadPool();
    private static int serial;
    static class SerialChecker implements Runnable {
        @Override
        public void run() {
            while(true) {
                //int serial;
                synchronized (serials) {
                     serial = SerialNumberGenerator.nextSerialNumber();
                }
                if (serials.contains(serial)) {
                    System.out.println("Duplicate: " + serial);
                    System.exit(0);
                }
                System.out.println(serial);
                serials.add(serial);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < SIZE; i++) {
            exec.execute(new SerialChecker());
            if (args.length > 0) {
                TimeUnit.SECONDS.sleep(new Integer(args[0]));
                System.out.println("No duplicates detected");
                System.exit(0);
            }
        }
    }
}

它可以停止,但当我取消注释//int serial;结果不同时,它无法停止。为什么这个临时变量的结果与外部类的静态变量不同。这是使用线程的原因吗?

SerialNumberGenerator的代码:

public class SerialNumberGenerator {
    private static volatile int serialNumber = 0;
    public static int nextSerialNumber() {
        return serialNumber ++; //Not thread-safe
    }
}

0 个答案:

没有答案