Silkking
Silkking

Reputation: 260

Simple thread program to understand synchronized, wait and notify

I'm looking at other examples here and in other sites and I'm not understanding what I'm doing wrong. I'm trying to do a program that one thread sets the value of an object to the values 1 to 10, but I want to wait for it to change the value until other thread reads it, so I can print them and have a list from 1 to 10.

My readThread run method just loops from 1 to 10 calling the following method:

private synchronized int receive() {
    try {
        wait();
        int value = this.mainThread.getValor();
        notify();
        return value;
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return -1;  
}

My writeThread run method just loops from 1 to 10 calling the following method:

private synchronized void send(int n) {
    try {
        this.mainThread.setValor(n);
        notify();
        wait();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

The main method is the following:

public static void main(String[] args) {
    MainThread mt = new MainThread();
    ReadThread rt = new ReadThread(mt);
    WriteThread wt = new WriteThread(mt);
    
    wt.start();
    rt.start();

}

The class MainThead has the property "valor" defined with its getter and setter

Thank you for your help

Upvotes: 1

Views: 60

Answers (1)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

There are a couple of obvious problems.

It looks as if you are synchronising on the same lock (there isn't enough code to be 100% sure). Generally you should create an object specifically to use as a lock.

send may be executed before receive. In that case the first notify will do nothing, and both threads will stall in wait.

In theory, there is no guarantee that wait will not wakeup spontaneously. For this and other reasons, you really want the wait inside a while loop.

Upvotes: 1

Related Questions