0

我是初学者,我必须为特定的 prob stmt 编写代码。我想用锁来实现它。事先,我了解了锁的工作原理及其方法。

在我下面的代码中,我需要第一个线程等待,第二个线程向第一个线程发出信号并唤醒。但是信号并没有唤醒我的等待线程。任何人都可以帮忙。

package com.java.ThreadDemo;

import java.util.Collection;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadEx {

    public static void main (String args[]) throws InterruptedException
    {
        ThreadMy mt[]=new ThreadMy[6];
        int a=1, b=2;
        mt[1] = new ThreadMy(a);
        mt[2] = new ThreadMy(b);
        mt[1].start ();
        Thread.sleep(100);
        mt[2].start ();
    }   
}
class ThreadMy extends Thread
{
    final ReentrantLock  rl = new ReentrantLock() ;
    Condition rCond = rl.newCondition();
    //private final Condition wCond = rl.newCondition();

    int i;
    int c;

    public ThreadMy(int a)
    {
        c=a;
    }

    public void run() 
    {
        System.out.print("\nThread "+c+" "+rl.isHeldByCurrentThread()+" "+rl.isLocked() );
        rl.lock();
    try
    {
    //for (i=0;i<2;i++)

    System.out.print("\nThread "+c+" "+rl.isHeldByCurrentThread()+" "+rl.getHoldCount() );
    try
    {
        if (c==1)
        {       
            System.out.print("await\n");
            rCond.await();
            //rCond.await(200, TimeUnit.MILLISECONDS);

            System.out.print("signal\n");
        }
        else
        {
            System.out.print("P");
            rCond.signal();
            Thread.sleep(2000);
            System.out.print("P1");
        }
        //rCond.signal();
    }
    catch ( InterruptedException e)
    {
        //System.out.print("Exception ");

        }

    }
    finally
    {
         rl.unlock();
    }
        System.out.print("\n run " + c);
    }

    }
4

1 回答 1

1

您没有在线程之间共享锁和条件。ThreadMy 的每个实例都使用自己的锁和条件对象运行。

于 2013-05-04T20:22:49.797 回答