I need to put two threads in java and have one part of my code wait for the other to end
thread in java
use of thread in java
how to start and stop a thread in java
java thread wait
java wait notify
creating multiple thread in java
synchronization in java
Good I have never used threads in java and what happens to me is that I try to call a class and then do something that changes some values of the class, but what happens that changes the values before unfortunately, and I would need to put two threads In java to be able to tell the values that I want to change, wait until the class finishes doing its function, I pass the code and I tell you what I want to do. Thank you.
public void mouseClicked(MouseEvent arg0) { try { // capa transparente if (auxContadorZoom < 3 && auxContadorZoom >= 0) { zoom.aumentar(100); for (int i = 0; i < 400; i++) { for (int j = 0; j < 400; j++) { image2.setRGB(i, j, zoom.enviar().getRGB(i, j)); } } label2.setIcon(new ImageIcon(zoom.enviar())); label2.removeAll(); label2.add(zoom); label2.repaint(); auxContadorZoom++; } // capa fondo if (auxContadorZoom1 < 3 && auxContadorZoom1 >= 0) { zoom1.aumentar(100); for (int i = 0; i < 400; i++) { for (int j = 0; j < 400; j++) { image.setRGB(i, j, zoom1.enviar().getRGB(i, j)); } } label.setIcon(new ImageIcon(zoom1.enviar())); label.removeAll(); label.add(zoom1); label.repaint(); auxContadorZoom1++; } } catch (Exception e) { // TODO: handle exception } //////This is where I want the 2 thread to wait for me to do this so that the zoom class finishes doing its things that I have previously sent zoom1.activarBoolTrue(); zoom.activarBoolTrue(); }
You should use a ReentrantReadWriteLock
synchronized
isn't appropriate since it will have the two threads blocking each other every time they run their code. wait
/notify
isn't appropriate since it will have the two threads waiting until the GUI event thread runs mouseClicked
, which means that your two threads will completely freeze up until someone clicks the relevant GUI element rather than running freely whenever mouseClicked
isn't in the special section you want to protect.
Since you want to block the two threads only when the separate GUI event thread calls the mouseClicked
method and not have the other two threads blocking each other, a ReentrantReadWriteLock
will work nicely.
Implementing it in your example
At the top of the file (just under the package
statement if you have one) containing the class that contains the mouseClicked
method:
import java.util.concurrent.locks.ReentrantReadWriteLock;
At the top of the class where you are defining variables:
public class … { public static final ReentrantReadWriteLock mouseClickedLock = new ReentrantReadWriteLock();
In the mouseClicked
method when you want to stop the other two threads, lock the writeLock
, try to execute your code, then unlock the writeLock
:
//////This is where I want the 2 thread to wait for me to do this so that the zoom class finishes doing its things that I have previously sent mouseClickedLock.writeLock().lock(); try { zoom1.activarBoolTrue(); zoom.activarBoolTrue(); } finally { mouseClickedLock.writeLock().unlock(); }
In the two threads, when you're doing something that shouldn't interrupt that special section of the mouseClicked
method, lock a readLock
, try to execute your code, then unlock that readLock
:
mouseClickedLock.readLock().lock(); try { // Your code here } finally { mouseClickedLock.readLock().unlock(); }
Make sure that the code using a read lock doesn't take that long to execute, since it will block mouseClicked
's special section until the read lock is unlocked. If a thread has a loop where it does the same thing over and over again, you should probably lock and unlock inside that loop so that it's waiting for one iteration of the loop to complete rather than all iterations.
Now the two threads can do what they want whenever they want to, except when the mouseClicked
method's special section is executing, where they will wait until that's finished.
Speed things up with a StampedLock
if you start using many more threads
If you begin to have many more threads than just two threads and the GUI event thread, a ReentrantReadWriteLock
can become slow. You can use a StampedLock
instead to speed things up.
It's a little more complicated to use, since you have to store a long
value called a stamp in order to later unlock the StampedLock
and since you can't have the same thread lock a StampedLock
twice without unlocking it in between the two lockings (i.e., it's not a reentrant lock) or else your program or some of its threads might permanently freeze up.
How to use Threads in Java (create, start, pause, interrupt and join), Java code examples to use threads (create, start, pause, interrupt and join threads) It cannot be used if your class needs to extend another class because Java is more flexible as Java allows a class can both extend another class Interrupting a thread can be used to stop or resume the execution of I need to wait for multiple threads to finish the run so as to accumulate results. Only after all the threads finish running should the foll message appear. How to wait for multiple thread to finish run (Threads forum at Coderanch)
You can use wait()/notify()
which are designed to block (release) a thread until (when) a specific condition is met, or join()
which allows one thread to wait until another thread completes its execution.
A possible solution would be sharing a common lock between two threads, say for example Thread-A and Thread-B. After some processing in Thread-A, call wait()
on a shared lock and thus Thread-A is waiting. When Thread-B finishes its calculation, call notifyAll()
on the same lock, and thus Thread-A resumes its processing.
final Object lock = new Object();
Thread-A
boolean isWorkDone = false; // Do some processing here! synchronized (lock) { try { while (!isWorkDone) { lock.wait(); // Thread-A waits here } isWorkDone = true; } catch (Exception e) { e.printStackTrace(); } } // Do rest of the processing here!
Thread-B
// Do your processing here. synchronized (lock) { lock.notifyAll(); // notify Thread-A that processing is done! }
Multithreading in java with examples, A thread is a light-weight smallest part of a process that can run concurrently with the TIMED_WAITING – A thread that is waiting for another thread to perform an Before we begin with the programs(code) of creating threads, let's have a In java we have the solution for this, put the calls to the methods (which needs to You could use a CountDownLatch from the java.util.concurrent package. It is very useful when waiting for one or more threads to complete before continuing execution in the awaiting thread. For example, waiting for three tasks to complete: CountDownLatch latch = new CountDownLatch(3); latch.await(); // Wait for countdown
Have you heard about locks? You need to synchronize on a lock.
Create a lock object with new Object()
, like:
Object lock = new Object();
and then use synchronized
around code sections that should wait for each other, like:
synchronized (lock) { … }
Make sure the threads can have access to that lock object.
Also, you can use a thread's join
method to wait for that thread to finish.
Multithreading and Concurrency - Java Programming Tutorial, Java has built-in support for concurrent programming by running multiple For example, while one thread is blocked (e.g., waiting for completion of an I/O In other words, while the counting is taking place, the EDT is busy and unable It is recommended to run the GUI construction codes on the EDT via the invokeLater() . In order to achieve so, the run methods of the two threads above have to be called one after the other, i.e. they need to be synchronized and I am achieving that using locks. The code works like this: t1.run prints the odd number and notifies any waiting thread that it is going to release the lock, then goes into a wait state.
Java notify() and wait() examples, This article contains two code examples to demonstrate Java concurrency. happens, the thread that is running it calls notify() from a block synchronized on the same object. } If you want someone to read your code, please put the code inside exactly is thread called putMessage() ). notify() should be places at the end of Each part of such program is called a thread. So, threads are light-weight processes within a process. Threads can be created by using two mechanisms : 1. Extending the Thread class 2. Implementing the Runnable Interface Thread creation by extending the Thread class We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class.
How to work with wait(), notify() and notifyAll() in Java , It wakes up one single thread that called wait() on the same object. So, if a notifier calls notify() on a resource but the notifier still needs to perform Once the wait() is over, producer add an element in taskQueue and called notifyAll() method. Note that both threads use sleep() methods as well for simulating time delays One tool we can use to coordinate actions of multiple threads in Java – is guarded blocks. Such blocks keep a check for a particular condition before resuming the execution. With that in mind, we'll make use of: Object.wait() – to suspend a thread. Object.notify() – to wake a thread up.
How to Join Multiple Threads in Java - Thread Join , Thread join() method is used to put thread on wait for joining. to implement scenarios like one thread is waiting for other threads to finish their task. make one thread wait for other, or serializing two function e.g. first load your cache and This doesn't ensure that the threads complete execution in the required order, only In this case, the current thread has to wait for all three threads t1, t2 and t3 completes before it can resume running. That’s the fundamentals of using threads in Java. You are now able to create, start, interrupt (to stop or resume) and join (to wait) threads. API References: Thread class Javadoc. Runnable interface Javadoc.
Comments
- Is
mouseClicked
being called by one of the two threads or is it being called by a mouse click? - is calling by a click, what I want is to do with threads to control it. Thank you
- OK. I'll add an answer below.
- the lock can be a method?
- The two threads are external to the
mouseClicked
method in the question.synchronized
isn't a valid solution since it causes the two threads to block each other when only themouseClicked
thread needs to block the two other threads. - How can I use it properly?
- This will cause the two external threads to block each other, rather than merely causing the
mouseClicked
method to block the two threads when part of it is executing.