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
https://stackoverflow.com/questions/67011783/simple-thread-program-to-understand-synchronized-wait-and-notify April 09, 2021 at 04:57AM
没有评论:
发表评论