Pergunta

I am new to threading and semaphors, and I have some problem in synchronizing threads. For example, in the following code I want to do a pretty simple thing. To let one thread run, while other waits. For example, if it starts with the first thread, I want the second to wait for the first one to finish and then start. I really don't know what am I doing wrong. Here is the code :

import java.io.*;
import java.util.concurrent.Semaphore;

public class ThreadTest {
    public static void main(String[] args) throws InterruptedException {
        Semaphore binaren = new Semaphore(1);
        Runnable t1 = new T2(binaren);
        Thread a = new Thread(t1);
        Thread a2 = new T1(binaren);
        System.out.println(binaren.availablePermits());
        a.start();
        a2.start();
    }
}
class Work {

    private static int a = 4;
    public synchronized static void QQR(String s1)
    {
        for(int i=0;i<100;i++)
        System.out.println(s1+" : "+(a++));
    }

}
class T1 extends Thread
{
    Semaphore sem;
    public T1(Semaphore s1)
    {
        sem=s1;
    }
    public void run()
    {   
        synchronized(this)  {
            if(!sem.tryAcquire()){
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            Work.QQR("T1");
            sem.release();
            notifyAll();
        }

    }


}
class T2 extends Thread
{
    Semaphore sem;

    public T2(Semaphore s1)
    {
        sem=s1;
    }

    @Override
    public void run() {
    synchronized(this)  {
        if(!sem.tryAcquire()){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        Work.QQR("T2");
        sem.release();
        notifyAll();
    }
}
}
Foi útil?

Solução

The problem is that notify and notifyAll only wake up threads holding locks on the monitor being notified. But the t1 and t2 instances are waiting on themselves and are never awoken. You can have them wait on the semaphore for this simple test or introduce a new shared object to see how it works.

Use

sem.wait();

and

sem.notifyAll();

Outras dicas

You can use Thread.join() on the first thread so that second thread will wait till the execution of this instance is not completed.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top