Java,使用同步方法的多线程 [英] Java, Multithreading with synchronized methods

查看:153
本文介绍了Java,使用同步方法的多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一些麻烦,让我的程序有时不会陷入僵局。我想我需要添加第三个同步方法版本,可以在调用ping之后释放另一个线程。代码如下。

I am having some trouble getting my program to not deadlock at times. I think I need to add a third synchronized method release, which can be used to release the other thread after a ping is called. code is below.

// Attempt at a simple handshake.  Girl pings Boy, gets confirmation.
// Then Boy pings girl, get confirmation.
class Monitor {
    String name;

    public Monitor (String name) { this.name = name; }

    public String getName() {  return this.name; }

     // Girl thread invokes ping, asks Boy to confirm.  But Boy invokes ping,
    // and asks Girl to confirm.  Neither Boy nor Girl can give time to their
    // confirm call because they are stuck in ping.  Hence the handshake 
    // cannot be completed.
    public synchronized void ping (Monitor p) {
      System.out.println(this.name + " (ping): pinging " + p.getName());
      p.confirm(this);
      System.out.println(this.name + " (ping): got confirmation");
    }

    public synchronized void confirm (Monitor p) {
       System.out.println(this.name+" (confirm): confirm to "+p.getName());
     }
}

class Runner extends Thread {
    Monitor m1, m2;

    public Runner (Monitor m1, Monitor m2) { 
      this.m1 = m1; 
      this.m2 = m2; 
    }

    public void run () {  m1.ping(m2);  }
}

public class DeadLock {
    public static void main (String args[]) {
      int i=1;
      System.out.println("Starting..."+(i++));
      Monitor a = new Monitor("Girl");
      Monitor b = new Monitor("Boy");
      (new Runner(a, b)).start();
      (new Runner(b, a)).start();
    }
}


推荐答案

某些操作需要获取两个不同的锁,确保没有死锁的唯一方法是确保尝试执行这些操作的每个线程以相同的顺序获取多个对象的锁。

When some operation needs to get hold of two different locks the only way of ensuring that there are no deadlocks is to make sure that every thread trying to perform those operations acquires the lock on the multiple objects in the same order.

要修复死锁,你需要像这样修改代码 - 不漂亮,但它可以工作。

To fix deadlock you need to modify the code like this - not pretty, but it works.

 public void ping (Monitor p) {
  Monitor one = this;
  Monitor two = p;
  // use some criteria to get a consistent order
  if (System.identityHashCode(one) > System.identityHashCode(two)) {
    //swap
    Monitor temp = one;
    one = two;
    two = one;
  }
  synchronized(one) {
       synchronized(two) {
           System.out.println(this.name + " (ping): pinging " + p.getName());
           p.confirm(this);
           System.out.println(this.name + " (ping): got confirmation");
        }
  }
}

这篇关于Java,使用同步方法的多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆