java多线程面试题,三个线程顺序打印ABC

来源:互联网 发布:苹果 知乎 编辑:程序博客网 时间:2024/05/17 23:32
package com.jinyi.medical.unsynch;import java.util.concurrent.TimeUnit;public class Test_ssss implements Runnable{    private String name;    private Object pre;    private Object self;    public Test_ssss(String name,Object pre,Object self){        this.name = name;        this.pre = pre;        this.self = self;    }    public static void main(String[] args) throws InterruptedException {        Object a = new Object();             Object b = new Object();             Object c = new Object();          Thread pa = new Thread(new Test_ssss("A",c,a));        Thread pb = new Thread(new Test_ssss("B",a,b));        Thread pc = new Thread(new Test_ssss("C",b,c));        pa.start();        TimeUnit.MILLISECONDS.sleep(100);        pb.start();        TimeUnit.MILLISECONDS.sleep(100);        pc.start();    }    public void run(){        int count = 10;        while(count>0){            synchronized (pre) {                synchronized (self) {                    System.out.print(name);                    count --;                    //释放锁,开启下一次的条件                    self.notify();                }                try {                    //给之前的数据加锁                    pre.wait();                } catch (Exception e) {                    // TODO: handle exception                }            }        }    }}
阅读全文
0 0
原创粉丝点击