美文网首页
哲学家问题示例

哲学家问题示例

作者: 恶魔幻心 | 来源:发表于2017-01-10 16:18 被阅读0次

    解决方法:无锁函数或者重入锁的中断或限时等待

    public classSimpleThreadextendsThread{

    staticObjecto1=newObject();

    staticObjecto2=newObject();

    inta;

    publicSimpleThread(inti) {

    a= i;

    }

    @Override

    public voidrun() {

    if(a==1){

    synchronized(o1){

    try{

    Thread.sleep(500);

    }catch(InterruptedException e) {

    e.printStackTrace();

    }

    synchronized(o2){

    System.out.println("哲学家A开始用餐;");

    }

    }

    }else{

    synchronized(o2){

    try{

    Thread.sleep(500);

    }catch(InterruptedException e) {

    e.printStackTrace();

    }

    synchronized(o1){

    System.out.println("哲学家B开始用餐;");

    }

    }

    }

    }

    public static voidmain(String[] args)throwsException{

    SimpleThread d1 =newSimpleThread(1);

    SimpleThread d2 =newSimpleThread(2);

    d1.start();

    d2.start();

    Thread.sleep(1000);

    }

    }

    相关文章

      网友评论

          本文标题:哲学家问题示例

          本文链接:https://www.haomeiwen.com/subject/wrokbttx.html