zoukankan      html  css  js  c++  java
  • 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();
        }
    }
  • 相关阅读:
    codeforces 980A Links and Pearls
    zoj 3640 Help Me Escape
    sgu 495 Kids and Prizes
    poj 3071 Football
    hdu 3853 LOOPS
    hdu 4035 Maze
    hdu 4405 Aeroplane chess
    poj 2096 Collecting Bugs
    scu 4444 Travel
    zoj 3870 Team Formation
  • 原文地址:https://www.cnblogs.com/frankyou/p/7340051.html
Copyright © 2011-2022 走看看