• 建立三个线程,A线程打印10次A,B线程打印10次B,C线程打印10次C


    http://www.cnblogs.com/x_wukong/p/4009709.html


    在原文的基础上,加入退出程序功能

    package Thread;
    
    /**
     * Created by sunyuming on 18/5/5.
     * 建立三个线程,A线程打印10次A,B线程打印10次B,C线程打印10次C,
     * 要求线程同时运行,交替打印10次ABC。这个问题用Object的wait(),notify()就可以很方便的解决。代码如下:
     */
    public class MyThread implements Runnable {
    
        private String name;
        private Object prev;
        private Object self;
    
        public MyThread(String name, Object prev, Object self) {
            this.name = name;
            this.prev = prev;
            this.self = self;
        }
    
        @Override
        public void run() {
    
            int i = 0;
            while (++i <= 10) {
                synchronized (prev) {
                    synchronized (self) {
                        System.out.println(name);
    
                        self.notifyAll();
                    }
    
                    try {
                        prev.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            System.out.println("done");
    
        }
    
    
        public static void main(String []args) throws InterruptedException {
    
            Object a = new Object();
            Object b = new Object();
            Object c = new Object();
    
            MyThread threadA = new MyThread("A", c, a);
            MyThread threadB = new MyThread("B", a, b);
            MyThread threadC = new MyThread("C", b, c);
    
            Thread A = new Thread(threadA);
            A.start();
            Thread.sleep(100);
            Thread B = new Thread(threadB);
            B.start();
            Thread.sleep(100);
            Thread C = new Thread(threadC);
            C.start();
    
            Thread.sleep(3000);
    
            A.interrupt();
            B.interrupt();
            C.interrupt();
        }
    }
    
    


  • 相关阅读:
    python 字符串内建函数之开头与结尾判断
    python 字符串内建函数之查找、替换
    python 字符串内建函数之大小写
    python 字符串切片
    python for循环
    python if语句
    python input( )
    python 变量命名规则
    DllMain
    静态库lib和动态dll的区别及使用方法
  • 原文地址:https://www.cnblogs.com/silyvin/p/9106576.html
Copyright © 2020-2023  润新知