zoukankan      html  css  js  c++  java
  • ReentrantReadWriteLock三个线程读数据,三个线程写数据

    /***
     * 三个线程读数据,三个线程写数据
     *
     */
    public class ReadWriteLockTest {
    
        public static void main(String[] args) {
            final ReadWrite rw = new ReadWrite();
            for (int i = 0; i < 3; i++) {
                new Thread() {
                    public void run() {
                        while (true) {
                            rw.read();
                        }
                    }
    
                }.start();
    
                new Thread() {
                    public void run() {
                        while (true) {
                            rw.write(new Random().nextInt(10000));
                        }
                    }
    
                }.start();
            }
    
        }
    }
    
    /**
     * 读和写要互斥,因此要把它们放在同一个类中
     *
     *
     */
    class ReadWrite {
        private Object data = null;// 共享数据,只能有一个线程写该数据,但可以有多个线程同时读该数据。
        ReadWriteLock rwl = new ReentrantReadWriteLock();
    
        /**
         * 读数据
         */
        public void read() {
    
            rwl.readLock().lock();
            try {
                System.out.println(Thread.currentThread().getName() + " be ready to read data!");
                Thread.sleep((long) (Math.random() * 1000));
                System.out.println(Thread.currentThread().getName() + "have read data :" + data);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                rwl.readLock().unlock();
            }
    
        }
    
        /**
         * 写数据
         *
         * @param data
         */
        public void write(Object data) {
    
            rwl.writeLock().lock();
            try {
                System.out.println(Thread.currentThread().getName() + " be ready to write data!");
                Thread.sleep((long) (Math.random() * 1000));
                this.data = data;
                System.out.println(Thread.currentThread().getName() + " have write data: " + data);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                rwl.writeLock().unlock();
            }
    
        }
    }
  • 相关阅读:
    程序猿之歌
    How to solve the problem : &quot;You have been logged on with a temporary profile&quot;
    LeetCode Jump Game
    hdu 3496 Watch The Movie
    matlab矩阵内存预分配
    【Windows socket+IP+UDP+TCP】网络基础
    <html>
    行为类模式(十):模板方法(Template Method)
    行为类模式(九):策略(Strategy)
    行为类模式(八):状态(State)
  • 原文地址:https://www.cnblogs.com/moris5013/p/11764826.html
Copyright © 2011-2022 走看看