Can wait/notify be used within one thread?
I’m mean I have a listener and in the moment when that listener gets called I wanna enable a thread to do his work.How could I do that?
UPDATE:My data is written in a database…and is written each time the listener is called.Now the thread that I’ve created reads that data and sends it somewhere….
Next…I get some other data and do the same thing….The other thread needs to know what was the last data he read it so he can start reading from where he left….
Take a look in here:
using wait and notify within one thread
This is how my problem looks like.Thx
I have the following:
synchronized (syncToken)
{
try {
syncToken.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("MyThread: " + s);
in MyThread….so when I do
MyThread t = new MyThread(syncToken);
t.start();
I put my thread on waiting…yes?
And when I do this:
syncToken.notify();
I get my thread back on track….but the execution of the next line is the one after wait()?
I mean this: System.out.println("MyThread: " + s); ????
When u notify a thred does he continues his execution with the line after wait()???Thx
The following is a simple example of concurrency between two different threads. In the example the main thread start a
MyThreadthread and every 3 seconds it sets a data to the MyThread instance and then MyThread prints it. The idea is to have a synchronized object that youwaiton it andnotifyin the end of the usage to other threads that they can use it:Test.java:
MyThread.java:
In this example, the main thread sets a string (every 3 seconds) and the MyThread thread prints it.
Adapt it to your needs, it shouldn’t be too hard.