Using thread.sleep in a for loop - java

I am using eclipse if it would make any difference. I am trying to update a label 10 times at the press of a button, and I want it to wait between updates. I am trying to use thread.sleep in a for loop, but it does not update the label until the for loop reaches an end.
The code is close to. It also has much more code in it to specify what to change the label to.
for (int i = 0; i < 10; i++) {
try{
thread.sleep(250);
}catch(InterruptedException ie) {
return;
}
panel.repaint();
}
Thanks, it really helped!

For the label to be updated, the main GUI event loop has to get its turn. But I'm guessing your code is running in the main thread, so the redrawing can't occur until your code is completely finished.
What you need to do is put your sleeping loop into a separate thread.
For this task, the SwingWorker class might be useful.

Swing has a single thread (commonly called the Swing thread) and all button presses, redraws, processing, updates, etc happen in that thread.
This means that if you block that thread (such as for example by sleeping in a loop) then it cannot redraw the screen until you finish.
You need to farm out the work to another thread such as by using SwingWorker or user a Timer to schedule the updates. Swing has a Timer class you can use that is designed for exactly this case, just tell it to call you back every 250ms and make the change in that callback.

May be i am not getting your exact problem otherwise below is the solution:
for (int i = 0; i < 10; i++) {
try{
panel.repaint();
thread.sleep(250);
// Or here if you want to wait for 250ms before first update
}catch(InterruptedException ie) {
return;
}
}
Thoguh SwingWorker is better option. Move above logic to SwingWorker thread. Sample code is below:
class Task extends SwingWorker<Void, Void> {
#Override
public Void doInBackground() {
for (int i = 0; i < 10; i++) {
try{
panel.repaint();
thread.sleep(250);
// Or here if you want to wait for 250ms before first update
}catch(InterruptedException ie) {
}
}
return null;
}
/*
* Executed in event dispatching thread
*/
#Override
public void done() {
// Do something if you want at the end of all updates like turn off the wait cursor
}
}

Related

I need to put two threads in java and have one part of my code wait for the other to end

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.
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!
}
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.

Thread is not Stopping/Interrupting

I have this code sample
public static class BlinkMe extends Thread {
int counter = 0;
protected boolean stop = true;
public void run() {
while (stop) {
counter++;
if (counter % 2 == 0) {
jLabel4.setVisible(true);
jLabel7.setVisible(true);
jLabel8.setVisible(true);
counter = 0;
} else {
jLabel4.setVisible(false);
jLabel7.setVisible(false);
jLabel8.setVisible(false);
if (jButton4.isEnabled() == false) {
stop = false;
jLabel4.setVisible(true);
jLabel7.setVisible(true);
jLabel8.setVisible(true);
if (jButton2.isEnabled() == false) {
stop = true;
jButton2.setEnabled(false);
}
}
}
}
}
}
I need to stop this Thread when I press my Stop Button...
Here's the code I'm using for the Button's function but it is not working. ***The Thread is not working at ll*
Here is the Button's function
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
BlinkMe b=new BlinkMe();
b.stop(); //here I have even used b.interrupt(); but doesn't stop the
}
There are many, many things wrong in this code.
you're accessing Swing components from a background thread. That's forbidden. Only the event dispatch thread is allowed to access Swing components
You're trying to stop() a thread, although this method is deprecaed and should never, ever be used, as the documentation explains
Instead of stopping the actual thread, you create a new instance of that thread class, and call stop() on that new instance.
You "blink" without any delay between the blink.
Your thread uses a stop variable, but this variable is never modified anywhere. Even if it was, it's not volatile, so you have a big chance of not seeing the modification, and thus not stopping the thread.
Read the Swing tutorial abount concurrency. And use a Swing Timer, which is designed to do that kind of thing, safely.
You are creating a new thread in actionPerformed and trying to stop the same, which was not started so far. Try calling stop in actual thread.
The initial value of your stop is "true". This means that when the thread starts, the run method executes but will not execute the while block because the condition will result to false right away.
First, you need to change your while loop into like this:
while(!stop) { /* the rest of your code */ }
Next, you need to create a method in your BlinkMe thread that would allow other objects in your program that would make it stop. The method would look something like this:
public void stopBlinking() {
stop = true;
}
Calling the above method will stop the infinite loop in the run method.
I don't think you will see a blinking effect when you run your program. It is because the loop executes very fast. I suggest you put a Thread.sleep(1000) somewhere in the loop so that there is time to reflect the blink effect visually.

Constant updating of Conway's Game of Life

I have trouble trying to click on a JButton and constantly updating the Conway's Game of Life. So what I have is firstly to give the rules from the Game of Life and simulate and calculate the position for the counters. Then update the frame by setting the background colour to the JButton, and then delay and repeat. But the problem is when I press the start button, it gets stuck due to the fact I was trying to use while loop.
There is a separate package called the AI_Processor which is just the simulation and calculation which is all done correctly, just the updating got some problems.
Code Parts:
public void updateFrame() {
AI.AI_Movement_Update();
addColour();
}
public void addColour() {
for (int i = 0; i < fieldHeight; i++) {
for (int j = 0; j < fieldWidth; j++) {
if (AI.getPosB(j, i) == true) {
testMolecules[i][j].setBackground(Color.green);
} else {
testMolecules[i][j].setBackground(Color.black);
}
}
}
}
Timer tm = new Timer(1000,this);
if (ae.getSource() == start) {
while(true) {
updateFrame();
tm.start();
}
}
You state:
But the problem is when I press the start button, it got stucked due to the fact i was trying to use while loop.
Then get rid of the while (true) loop since all this does is tie up the Swing event thread rendering your GUI useless. You have a Swing Timer, and you could call the model's update method in the timer's ActionListener so that it is called with each tick of the timer, and then you would not need the while loop. Other options include keeping the while (true) loop, but calling it in a background thread, but if you do this, take care to update your GUI on the Swing event thread only.
...Sorry for the formatting though...
I have formatted your code for you, but for future reference you will want to read the help section of this site regarding how to format questions and containing code. Also have a look here.
Other random thoughts:
Regarding Timer tm = new Timer(1000,this);, I try to avoid having my GUI classes implement listener interfaces as it forces the class to do too much, breaking the Single Responsibility Principle. Better to use either a separate listener class, a Control class that assigns listeners, or an anonymous inner class.
For more information on Swing threading issues, please see Lesson: Concurrency in Swing
For more on anonymous inner classes, again, get rid of the while (true) bit and instead try something like:
// note that TIMER_DELAY is a constant, and needs to be smaller than 1000, perhaps 20?
Timer tm = new Timer(TIMER_DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
updateFrame();
}
});
// the start call below can only be called inside of a method or a constructor
tm.start();
EDIT:
sorry, previous solution was bad :-(
EDIT:
you could use anonymous inner class for this
see http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
see http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html
If you use Timer, then you should pass an instance of ActionListener
Timer creates a new Thread, so while is not neccessary...
Not tested:
public void updateFrame(){
AI.AI_Movement_Update();
addColour();
}
public void addColour() {
for (int i = 0; i < fieldHeight; i++) {
for (int j = 0; j < fieldWidth; j++) {
if (AI.getPosB(j, i) == true) {
testMolecules[i][j].setBackground(Color.green);
} else {
testMolecules[i][j].setBackground(Color.black);
}
}
}
}
if(ae.getSource() == start)
new Timer(1000,new ActionListener(){
updateFrame();
}).start();

SWT progress dialog while performing a long operation in the UI thread?

I have a long operation that cannot be moved from the SWT UI thread. I know, it's gross, but that's how it is. I would like to display a progress bar of some sort for said long operation. I have tinkered around with org.eclipse.jface.dialogs.ProgressMonitorDialog. I'm not giving it an IRunnableWithProgress because, like I said, the long op is in the UI thread. And thus, we have something like...
Shell shell = new Shell();
ProgressMonitorDialog progressDialog = new ProgressMonitorDialog(shell);
progressDialog.open();
IProgressMonitor progressMonitor = progressDialog.getProgressMonitor();
int workLoad = 10;
progressMonitor.beginTask(message, workLoad);
for(int i = 0; i < workLoad; ++i) {
progressMonitor.worked(1);
progressMonitor.subTask("Subtask " + (i+1) + " of "+ workLoad + "...");
if(progressMonitor.isCanceled()) {
break;
}
// Do some work.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
progressMonitor.done();
progressDialog.close();
This works, but obviously does not update smoothly and at times is laggy to moving and clicking cancel. I thought maybe I could manually update the UI in this instance by creating a thread containing the requisite...
while(!shell.isDisposed()) {
if(!display.readAndDispatch()) {
display.sleep();
}
}
...in the run method, but much to my chagrin I bumped into...
Exception in thread "Thread-16" org.eclipse.swt.SWTException: Invalid thread access
Turns out you can't do that in just any old thread, those calls have to originate in the UI thread. Back to square one.
Does anyone know if I can trick the system? Like make my little thread appear to be the UI thread? Or just any other suggestions would be cool.
Thanks,
jb
The only way to have a responsive UI is to call Display.readAndDispatch() in the UI thread, period. Normally, RCP takes care of it for you, or the main method of your application, but if you are running something on the UI thread, they can't, so you have to.
Note that there can only be one UI thread, so if you could "make my little thread appear to be the UI thread" your original long-running task would not be running in the UI thread after all.

Have threads run indefinitely in a java application

I am trying to program a game in which I have a Table class and each person sitting at the table is a separate thread. The game involves the people passing tokens around and then stopping when the party chime sounds.
how do i program the run() method so that once I start the person threads, they do not die and are alive until the end of the game
One solution that I tried was having a while (true) {} loop in the run() method but that increases my CPU utilization to around 60-70 percent. Is there a better method?
While yes, you need a loop (while is only one way, but it is simplest) you also need to put something inside the loop that waits for things to happen and responds to them. You're aiming to have something like this pseudocode:
loop {
event = WaitForEvent();
RespondToEvent(event);
} until done;
OK, that's the view from 40,000 feet (where everything looks like ants!) but it's still the core of what you want. Oh, and you also need something to fire off the first event that starts the game, obviously.
So, the key then becomes the definition of WaitForEvent(). The classic there is to use a queue to hold the events, and to make blocking reads from the queue so that things wait until something else puts an event in the queue. This is really a Concurrency-101 data-structure, but an ArrayBlockingQueue is already defined correctly and so is what I'd use in my first implementation. You'll probably want to hide its use inside a subclass of Thread, perhaps like this:
public abstract class EventHandlingThread<Event> extends Thread {
private ArrayBlockingQueue<Event> queue = new ArrayBlockingQueue<Event>();
private boolean done;
protected abstract void respondToEvent(Event event);
public final void postEvent(Event event) throws InterruptedException {
queue.put(event);
}
protected final void done() {
done = true;
}
public final void run() {
try {
while (!done) {
respondToEvent(queue.take());
}
} catch (InterruptedException e) {
// Maybe log this, maybe not...
} catch (RuntimeException e) {
// Probably should log this!
}
}
}
Subclass that for each of your tasks and you should be able to get going nicely. The postEvent() method is called by other threads to send messages in, and you call done() on yourself when you've decided enough is enough. You should also make sure that you've always got some event that can be sent in which terminates things so that you can quit the game…
I would look into Locks and Conditions. This way you can write code that waits for a certain condition to happen. This won't take a lot of CPU power and is even much more efficient and better performing than sleeping .
To make a thread run for an infinite time:
final Object obj = new Object();
try {
Thread th = new Thread(new Runnable() {
public void run() {
synchronized(obj) {
try {
System.out.println("Waiting");
obj.wait();
System.out.println("Done waiting");
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
});
th.start();
System.out.println("Waiting to join.");
// Dont notify; but wait for joining. This will ensure that main thread is running always.
th.join();
System.out.println("End of the Program");
} catch(Exception ex) {
ex.printStackTrace();
}
You may add Thread.sleep() with appropriate time to minimize useless loop iterations.
Another solution is using synchronization. While threads are not required to do anything, they enter into a sleeping state on a monitor using the wait() method, and then when the turn comes, required thread is woken up by the notify() method.
Actor model seems suitable for this scenario. Each person sitting on the table and the table itself can be modelled as actors and the event of passing the tokens and starting and stopping of the game can be modelled as messages to be passed between the actors.
As a bonus, by modelling the scenario as actors you get rid of explicit manipulation of threads, synchronization and locking.
On JVM I will prefer using Scala for modelling actors. For Java you can use libraries like Kilim. See this post for a comparison of Actor model related libraries in Java.
One Way is to use while loop but keep a check i.e
while(true){
if(condition!=true){
Thread.sleep(time);
}else{
break;
}
}
This way if your condition says game is not over it will keep person thread at sleep and memory consumption will be very low.
You should test for a condition in the while loop:
while (!gameOver)
{
do_intersting_stuff();
}
Heavy CPU load is typical for busy wait. Is your loop actually just checking a flag over and over, like
while (!gameOver)
{
if (actionNeeded)
{
do_something();
}
}
you might change to another notification system to sleep and wake up, as this just burns CPU time for nothing.

Categories