2012-03-09 27 views
0

。我用java写了一个同步代码。有两类,第一类增加1000,第二类增加10。这个过程应该重复100次。 虽然我写了循环循环,但它们不起作用。我有一个死锁同步,请大家帮忙启动循环周期

下面是代码:

public class thread 
{ 
    static int count = 100; 
    public static void main(String[] args) 
    { 
    Thread thread1 = new Thread(new XThread()); 
    Thread thread2 = new Thread(new YThread()); 

    thread1.start(); 
    thread2.start(); 
    synchronized(thread2) 
     { 
     thread2.notify(); 
     } 

    } 
} 
class XThread extends Thread { 
    static long sum=0; 

    static int i; 
    synchronized public void run() { 

    sum=5+1000; 
    System.out.println(i+" "+"Thread 1"+" "+sum); 

    { 
     for(i= 0; i < lab5.count; i++) 
     { 
      try { 
      { 
       System.out.println("-----------");     
       this.wait(); 
      } 



      } 
      catch (InterruptedException ex) 
      { 
       sum=sum+1000; 
       System.out.println(i+" "+"Thread 1"+" "+sum); 
       notify(); 

      } 
     } 
    } 

    } 
} 

class YThread extends Thread 
{ 
    static long sum; 
    static int i; 
    synchronized public void run() 
    { 
    sum=5+10; 
    System.out.println(YThread.i+" "+"Thread 2"+" "+YThread.sum); 
    for(i=0; i < lab5.count; i++) 
     { 

     try 
      { 
      { 
       System.out.println("------------"); 
       this.wait(); 
      } 

      } 

     catch (InterruptedException ex) 
      { 
      sum=sum+10; 
      System.out.println(YThread.i+" "+"Thread 2"+" "+YThread.sum); 
      notify(); 

      } 
     } 
    } 
} 
+0

这是功课? – 2012-03-09 19:33:08

+0

看起来像一个... – 2012-03-09 19:33:53

+0

我只是工作的一些exsercices ...和我坚持了僵局。 – PKb 2012-03-09 19:37:30

回答

1

在你的代码在你的主题覆盖的run方法调用wait

不幸的是,没有人在等待的对象上调用notify方法。

这是因为在您的main中,您将XYThread重新包装为通用Thread对象。

因此,致电thread2.notify()将信号发送给错误的对象(不是锁定的YThread,而是包装器对象)。

更改声明

Thread thread1 = new XThread(); 
Thread thread2 = new YThread(); 

你的程序仍然会锁定(因为你不是notifying线程足够的时间),但它至少还可以得到。在我的最后一句话中,请注意may。这是因为线程2的notify可能在线程调用其第一个wait之前发送。