zoukankan      html  css  js  c++  java
  • 2个线程顺序工作

    2个线程,一个线程先写,然后另外一个线程读,以此循环。

    static int i = 8;
    static Object obj = new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread read = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; j < 100; j++) {
                    synchronized (obj) {
                        System.out.println("read:" + i);
                        
                        obj.notify();
                        
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        
                    }
                }
            }
        });
        Thread write = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; j < 100; j++) {
                    synchronized (obj) {
                        i = j;
                        System.out.println("write:" + i);
                        
                        obj.notify();
                        
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        write.setName("write");
        read.setName("read");
        
        write.start();
        Thread.sleep(10);
        read.start();
    }
  • 相关阅读:
    最详细的 paypal 支付接口开发--Java版
    Java IO--NIO(二)
    Java IO--NIO(一)
    Java IO--BIO
    ForkJoinPools
    ScheduledThreadPool
    SingleThread
    CachedThreadPool
    ForkJoinPool
    WorkStealingPool
  • 原文地址:https://www.cnblogs.com/allenwas3/p/8644690.html
Copyright © 2011-2022 走看看