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();
    }
  • 相关阅读:
    Out of Hay POJ
    Sum Problem hdu 1001
    N! hdu 1042
    线性表的链式表示和实现(插入删除建空合并)
    NYOJ 1007
    NYOJ 954
    NYOJ 998
    NYOJ 455
    NYOJ 975
    数据结构复习0---线性表
  • 原文地址:https://www.cnblogs.com/allenwas3/p/8644690.html
Copyright © 2011-2022 走看看