Java 共享数据读写(多线程)

public class StopThread {

    // 静态字段的读写不必须要同步才能生效,尽管读写是原子的(atom)
    private static boolean stopRequested;

    /**
     * 对静态共享字段的写进行同步
     */
    private static synchronized void requestStop() {
        stopRequested = true;
        System.out.println("stopRequested");
    }

    /**
     * 对静态共享字段的读进行同步
     * @return boolean
     */
    private static synchronized boolean stopRequested() {
        return stopRequested;
    }

    public static void main(String[] args) throws InterruptedException {
        Thread bkThread = new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 0;
                while (!stopRequested()) {
                    System.out.println(i);
                    i++;
                }
            }
        });
        
        // 启动异步线程
        bkThread.start();
        
        // 主线程休眠1秒
        TimeUnit.SECONDS.sleep(1);
        
        // 发出stop指令(stopRequested = true)
        requestStop();
    }
}
原文地址:https://www.cnblogs.com/frankyou/p/7340051.html