• 建立三个线程,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();
        }
    }
    
    


  • 相关阅读:
    解决eclipsehelios中Errors running builder JavaScript Validator的问题
    oracle sequence cache
    离开页面前调用Js方法
    精典的148句话
    DB2 应用
    现有portal项目(商业的和开源的)解决方案及优缺点
    管理铁律
    myeclipse 6.0 弹出 Multiple Errors have Occurred 错误
    绝对经典的表记录操作(超越版)
    DB2中不同于其它数据库的操作
  • 原文地址:https://www.cnblogs.com/silyvin/p/9106576.html
Copyright © 2020-2023  润新知