I want to draw number of rectangles one after another using a specific time .
I use thread.sleep() method but it is directly stop working of thread and not resume.
Use Thread.sleep(long millis) instead, on the worker thread.
Specify number of milliseconds in sleep:
Thread.sleep(2000); // two seconds
Note that you need to handle InterruptedException.
You need to put the sleep in another thread. If you put the sleep in your GUI-thread, the GUI will freeze.
edit: My bad, will leave this here as a side note comment instead.
You could use Timer and TimeTask classes.
See this example.
Look at the java executors. These can run for a fixed time. Inside each executor unit you can then draw a rectangle. (on the EDT) This API document has a useful example at the top
You should instantiate each draw in a separate thread. Create the separate thread for every loop of the sleep.
This way, you would separate the thread for looping, and the thread for drawing. Thus, removes the freezing.
public class RunTest implements Runnable{
#Override
public void run() {
// codes for drawing
}
}
And in your main:
try {
while (true) {
Thread t = new Thread(new RunTest());
t.start();
}
} catch (InterruptedException iex) {}
This will create an infinite number of Threads for you drawing. Just modify this loop.
See here for threads.
Related
I'm new to multithreading, so excuse my potentially silly question.
I need to use several threads in my app. However, virtually all of these threads will modify the UI. I've successfully used runOnUiThread, but what I fear is that if I create different threads of the same type, they will all be running on one thread, the "Ui thread", which may slow down my app.
Is this true, or am I greatly misunderstanding?
My thread which I will essentially multiply:
private void goldPerSecondMethod() {
new Thread() {
public void run() {
while (goldCount < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
goldCount += 0.1f;
textGoldCount.setText(goldCount + " Gold");
textGoldCount.setGravity(Gravity.CENTER);
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
All help is appreciated!
I need to use several threads in my app.
Why? For example, there is no need for a thread that you create yourself in the code sample you have above. Use a postDelayed() loop (no threads), or use ScheduledExecutorService (threads, but you don't have to create them) for timing.
what I fear is that if I create different threads of the same type, they will all be running on one thread, the "Ui thread", which may slow down my app.
I have no idea what "the same type" means. In your code snippet above, everything in the Runnable that you pass to runOnUiThread() will be executed on the main application thread (sometimes called the UI thread). Everything else in your outermost run() will be executed on this background thread.
It is correct that you need to run UI updates on the UI thread. Hence you do textGoldCount.setText(...) on the UI thread. Technically, this is a correct approach.
However, it's unnecessary to call setGravity(...) every time you update the text field. You should be able to set the gravity once. Best place would be probably your XML view description.
At the end you don't do much heavy work on the UI thread, except updating the text view's text. As every thread is sleeping 1 second before updating the UI again, there should be no notable delay for the user as long as you don't run too many of those threads.
Thread d = new Thread(new Runnable() {
#Override
public void run() {
while(true);
}
});
d.start();
How can I quit the infinite loop, without changing the code inside the method public void run(),
and without using d.stop(); (deprecated method).
P.S: I'd prefer publishing the whole exercise details I need to do. That's kinda the thing I need to dill with. They gave me a function which sometimes goes inside infinite loop, and I can't change that method.
How can I quit the infinite loop, without changing the code inside the method public void run(), and without using d.stop(); (deprecated method).
I assume this is some sort of academic or interview question. If you can't change the thread code then you can't add an interrupt or volatile boolean check. And you can't call .stop() (which is btw deprecated and never a good idea).
The only thing I can think of is to set the thread be a daemon thread.
Thread d = new Thread(new Runnable() { ... });
...
d.setDaemon(true);
d.start();
It needs to be set daemon before it is started. This is a hack but maybe within the framework of the question. This won't kill the thread immediately but if the last non-daemon thread exits then the thread will be killed by the JVM.
Of course you can also remove the .start() line but that seems outside the realm of the question. System.exit(0); would also bring down the JVM as #MattBall pointed out but that also seems like cheating.
Outside of killing the JVM running the thread, I don't see how you can quit the loop.
A better method would at minimum check for thread interruption:
Thread d = new Thread(new Runnable() {
#Override
public void run() {
while(!Thread.currentThread().isInterrupted());
};
d.start();
d.interrupt();
You can't. The only way to stop a thread asynchronously is the stop() method. But without that, you can't.
Without .stop() you need to change the code in the thread itself. see here here for some ideas.
Always avoid while(true). Try while(running). That condition should determine the life of the loop. Then when you set running = false, the life of the loop ends and subsequently the thread.
I have a question regarding calling methods after a certain amount of delay.
I want to call a Java method exampleFunction() after a delay of about 10 seconds. I have looked for solutions online and have come across the ScheduledThreadPoolExecutor(). So I have used this, but the thing is, once the function runs after 10 seconds, it doesn't exit from the thread. Is there any way I can exit from the thread? Or can I run the ScheduledThreadPoolExecutor() on the current thread instead of creating a new thread?
class Test {
...
exampleFunction();
...
public void exampleFunction() {
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.schedule(new Runnable() {
public void run() {
...do something here...
}
}, 10, TimeUnit.SECONDS);
}
}
So is there any way I can exit this thread after exampleFunction runs after a delay of 10 seconds? Or can I have the ScheduledThreadPoolExecutor use the current thread instead of creating a new one?
Or is there another way I can approach this problem? I want to be able to run exampleFunction() after 10 seconds on the current thread, instead of creating a new thread.
Edit: I think it may not be a thread issue. I'm still trying to figure out the problem is. Thanks everyone for your suggestions and advice.
EDIT: Can I pass an argument to exampleFunction() and then use it inside public void run()?
I believe your problem may be that you are not shutting down the executor after your submit the job to it.
exec.schedule(...);
exec.shutdown();
The jobs that have been submitted will continue to run but you have to shutdown the service after you've submitted the last job to it.
Based on all the comments and confusion, any answer is just a guess.
What I think you want:
The UI thread to invoke exampleFunction
'exampleFunction` to schedule a task for 10 seconds later and return immediately
In 10 seconds time, to have the run method be invoked on the UI thread
In Swing, this is done by using SwingUtilities.invokeLater.
ExampleFunction would look like this:
public void exampleFunction() {
new Thread() {
public void run() {
TimeUnit.SECONDS.sleep(10); //Will need a try/catch
SwingUtilities.invokeLater(new Runnable() {
public void run() {
...do something here...
}
});
}
}.start();
}
Note: SwingUtilities.invokeAndWait could also be used.
Note 2: Although not usually advised, a simple Thread here is simpler than making a new Thread pool.
Thread.sleep can be used if merely wishing to making the current thread block. If you do use a pooled executor, make sure to use it as a pooled executor - not one per (new) thread. To "exit" from a thread, just let execution run out of run. If using Swing, use the EDT.
I was wondering which would be the most efficient approach to implement some kind of background task in java (I guess that would be some kind of nonblocking Threads). To be more precise - I have some java code and then at some point I need to execute a long running operation. What I would like to do is to execute that operation in the background so that the rest of the program can continue executing and when that task is completed just update some specific object which. This change would be then detected by other components.
You want to make a new thread; depending on how long the method needs to be, you can make it inline:
// some code
new Thread(new Runnable() {
#Override public void run() {
// do stuff in this thread
}
}).start();
Or just make a new class:
public class MyWorker extends Thread {
public void run() {
// do stuff in this thread
}
}
// some code
new MyWorker().start();
You should use Thread Pools,
http://java.sun.com/docs/books/tutorial/essential/concurrency/pools.html
Naïve idea : you might be able to create Thread, give it a low priority, and do a loop of :
doing a little bit of work
using yield or sleep to let other threads work in parrallel
That would depend on what you actually want to do in your thread
Yes, you're going to want to spin the operation off on to it's own thread. Adding new threads can be a little dangerous if you aren't careful and aware of what that means and how resources will interact. Here is a good introduction to threads to help you get started.
Make a thread. Mark this thread as Daemon. The JVM exits when the only thread running are all daemon threads.
I need to do some clean up work when I am going to terminate a looped thread. Such as saving a buffer so I can continue later.
PseudoCode:
private class CalculatePI(Byte[] resume) implements Runnable{
public void Run(){
while(true){
resume=resumeCalculating(resume);
}
}
}
Thread calculator= new Thread(new CalculatePI(Byte[] resume));
Thread.sleep(200);
//And now I want to kill calculator
So what's the best way implement this?
Use a flag: But the problem is what if resumeCalculating() takes (EDIT: a long time) forever to end?
Put an exception into calculator, how?
Can I use event listeners or something? I thought they were used for GUIs
Just stop it? And Class Thread includes some kind of deconstructor that will be called when the thread is terminated and I could do the processing there?
EDIT by Owner:
I know I can use a flag. But consider this:
public void Run(){
while(true){
resume=calculate_stepone(resume); //takes one minute
resume=calculate_steptwo(resume); //takes two minutes
resume=calculate_stepthree(resume); //takes three minutes
resume=calculate_steplast(resume); //takes four minutes
}
}
Is putting a if(flag) saveResultsAndExit(); between every line practical or pretty?
I just want to throw away the half-processed results, and save the previous results.
The proper way to stop a thread is to interrupt it.
If the task running in the thread is performing IO or is using sleep then it will receive the signal (InterruptedException at that point); else the task should regularly poll to see if its interrupted.
Lets adapt the original poster's psuedocode:
private class CalculatePI(Byte[] resume) implements Runnable{
public void Run(){
while(!Thread.interrupted()) { //###
resume=resumeCalculating(resume);
}
}
}
Thread calculator= new Thread(new CalculatePI(Byte[] resume));
calculator.run(); //###
//...
//And now I want to kill calculator
calculator.interrupt(); //### sends the signal
//...
calculator.join(); //### actually waits for it to finish
Answer to 1.: You can process the abort flag in resumeCalculating() too.
It is probably best to use a flag, wait for a while for the thread to end, and if it hasn't (resumeCalculating hasn't returned) kill the thread manually. It is probably best not to involve too much thread based logic in resumeCalculating, it really depends on how it is implemented as to how easy it is to abort halfway through an operation.
Design your program so that resumeCalculating does NOT take forever to continue. Also, synchronize access to your flag.