java start one background thread after another complete - java

I saw this question: how to run one thread after complete another thread , but the answer to it is not appropriate for me.
I have such kind of java code for Android:
public void startTask(Runnable r)
{
running = true;
Log.i(tag, "-----------start.Runnable-----------");
Thread first = new Thread(r);
first.start();
Thread second = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
running = false;
}
});
}
first Thread takes as param Runnable object with some hard operation which I am processing in background service. So, when I call method: startTask() I set running = true; to prevent double executing tasks. But, also, I need right after completeness of first thread start second thread to set running = false; to enable other operations to execute.
How can I wait completeness of first thread by second not to freeze main thread?? Thanks!

You may use SingleThreadExecutor.
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(runnable1);
executor.execute(runnable2);

Try this:
final Thread first = new Thread(r);
first.start();
Thread second = new Thread(new Runnable() {
#Override
public void run() {
first.join();
// TODO Auto-generated method stub
running = false;
}
});
second.start();
I changed:
add final keyworrd for 'first'
wait finish of first thread by #join at begin of second thread.
start sencond thread soon.

I'm not an Android programmer but something like this may work:
private volatile boolean running = false;
public void startTask(final Runnable r)
{
running = true;
Log.i(tag, "-----------start.Runnable-----------");
Runnable runme = new Runnable() {
#Override
public void run() {
try {
r.run();
} finally {
running = false;
}
}
};
new Thread(runme).start();
}
It needs only one thread to run the task and then clear the running flag. Note the use of volatile in the declaration of running, as this variable is being read and written from multiple threads.

Related

Stop and restart a already running thread

The Thread should end if I press a button, which sets the isButtonPressed to true.
My problem is, that if a want to start the thread with thread.start(runnable) by clicking the button, I get this: IllegalThreadStateException: Thread already started (I thought the thread was terminated after the break because the the loop is over, but it seems that I am wrong).
Thread thread = new Thread(runnable);
thread.start(runnable);
The runnable Runnable:
Runnable runnable = new Runnable() {
#Override
public void run() {
time = 10;
for (int i = 10; i <= 10; i--) {
handler.post(new Runnable() {
#Override
public void run() {
txt_Time.setText(String.valueOf(time));
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
if (isButtonPressed) {
break;
}
if (time == 0) {
resetVisibleState();
break;
} else {
time--;
}
}
}
};
Thanks for your help!
Java threads are not restartable. For what you are trying to achieve, you could create a new thread each time, or you could look at an ExecutorService. Just create a single threaded executor (Executors.newSingleThreadExecutor), and submit your runnable to it every time you need it to run.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(runnable);
From my understanding you need to start a new thread. You cannot re-start a thread that has ran its course.
Since you are correctly stopping the old one via your isButtonPressed. You should just be able to start a new instance of the thread in its place
Take a boolean variable and wrap the contents you need to run continusly in the thread with a while loop that runs forever till Run is set to false then on clicking the button set the variable to false, for example :-
volatile boolean run = true;
Thread t = new Thread()
{
while(run)
{
// whatever is here runs till Run is false
}
}
t.start();
/*now when the button is pressed just trigger Run as false and the thread will be ended
later call t.start() when you need to start the thread again.*/

How to stop a thread as soon as a certain amount of time expires? [duplicate]

This question already has answers here:
How to properly stop the Thread in Java?
(9 answers)
Closed 9 years ago.
I am having a problem trying to stop a thread instantly after a certain amount of time has elapsed, because thread.stop and similar others have been depreciated.
The thread that I am trying to stop uses my mouse and I need to stop it so that I can use my mouse in other ways.
What I was thinking is the code below, which was just to make another thread to watch how long the main thread has been running and if it is alive, stop it, but I can't accomplish this.
public void threadRun(int a) {
Thread mainThread = new Thread(new Runnable() {
#Override
public void run() {
// does things with mouse which may need to be ended while they
// are in action
}
});
Thread watchThread = new Thread(new Runnable() {
#Override
public void run() {
if (timeFromMark(mark) > a) {
if (mainThread.isAlive()) {
// How can I stop the mainThread?
}
}
}
});
}
You need to define a class for your second thread that extends runnable and pass the first thread as an argument.
Then you can stop the first thread.
But instead of doing this manually, have a look at the Java ThreadPoolExecuter and its awaitTermination(long timeout, TimeUnit unit) method. (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html )
Will save a lot of work.
ExecutorService executor = Executors.newFixedThreadPool(1);
Runnable r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("doing stuff");
Thread.sleep(10000);
System.out.println("finished");
} catch (InterruptedException e) {
System.out.println("Interrupted before finished!");
}
}
};
executor.execute(r);
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.SECONDS);
executor.shutdownNow();
} catch (InterruptedException e) {
//
}
System.out.println("Thread worker forced down. Continue with Application...");
Produces:
doing stuff
Interrupted before finished!
Thread worker forced down. Continue with Application...
Last two messages are nearly equal in terms of time and may change positions (its two different threads, continuing)
Java has deprecated methods for explicitly killing another thread (like Thread.stop / Thread.destroy). The right way is to make sure the operations on the other thread can handle being told to stop (for example, they expect an InterruptedException, which means you can call Thread.interrupt() in order to stop it).
Taken from How do I kill a thread from another thread in Java?
Killing/stopping threads is a bad idea. That's why they deprecated those methods. It's better to ask the thread to stop. E.g., something like the example below. (But note: if "do_something()" takes a long time, then you might want to use an interrupt to abort whatever it is.)
import java.util.concurrent.atomic.AtomicBoolean;
public class Stoppable {
private AtomicBoolean timeToDie = new AtomicBoolean(false);
private Thread thread;
public void start() {
if (thread != null) {
throw new IllegalStateException("already running");
}
thread = new Thread(new Runnable() {
public void run() {
while (!timeToDie.get()) {
// do_something();
}
}
});
thread.start();
}
public void stop() throws InterruptedException {
timeToDie.set(true);
thread.join();
thread = null;
}
}

Java code Multiple Thread, Wait to start other

I a trying to find out, after complete first thread completely than start second thread, after complete second thread than start third thread, Please help me!!
Here is my code:
public class wait {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("First Thread");
createtheard2();
}
public static void createtheard2() {
try {
System.out.println("Second Thread");
} catch(Exception error1) {
error1.printStackTrace();
}
createtheard3();
}
public static void createtheard3() {
try {
System.out.println("Third Thread");
} catch(Exception error1) {
error1.printStackTrace();
}
}
}
After complete first thread, than start second thread, after complete second thread, than start third thread, Please help me!! Thanks!!
Implement Runnable
public class ThreadDemo implements Runnable {
public void run() {
//Do this what you need
}
}
Use join to wait while thread will be completed.
Thread t1 = new Thread(new ThreadDemo());
// this will call run() function
t1.start();
// waits for this thread to die
t1.join();
Thread t2 = new Thread(new ThreadDemo());
// this will call run() function
t2.start();
// waits for this thread to die
t2.join();
From http://docs.oracle.com/javase/tutorial/essential/concurrency/join.html
t.join() causes the current thread to pause execution until t's
thread terminates.
In your case paused by join method invocation thread will be Main thread.
I think what you need is if task 1 (thread in your terms) success, run task2 else wait for task1. consider the following.
public class Process{
public static void runProcess1() {
boolean done = false;
do {
// make done=true after task1 is done
} while (done);
runProcess2();
}
public static void runProcess2() {
boolean done = false;
do {
// make done=true after task2 is done
} while (done);
runProcess3();
}
public static void main(String[] args) {
runProcess1();
}
}
As it was pointed out, using threads in this case does not make sense as you are executing tasks sequentially.
However, it is possible to have a single thread running at a time with SingleThreadExecutor
For example, you
Add your threads to a "todo list" (ArrayList will do the job)
Schedule a task (ExecutorService.execute())
Wait for the scheduled task to complete (Thread.join())
Drop the thread from the "todo list" tasks.remove(currentTask);
Pick the next task or go to step 7 if all has been finished
Go back to step 2
Kill the ExecutorService (ExecutorService.shutdown())
Alternatively, you could use ExecutorService.invokeAll() using a single thread executor.
You could even simply run the tasks directly in a loop, invoking start(), however, I'd really recommend against using concurrency where it is not a necessity.

Cyclic Thread start in Android

I have a for cylce that calls threads:
if(toModify[j]==1)
{
getUpdate(methods_list[j],username, password);
}
getUpdate is a method which contains something like this:
new Thread(new Runnable() {
public void run() {
// *** some operations***
}
}).start();
Through for cycle I can run each Thread simultaneously.
But if I want that each Thread starts only after the previous has stopped, can I use the following trick?
if(toModify[j]==1)
{
int returnValue = getUpdate(methods_list[j],username, password);
}
and add at the end of getUpdate method this code line (outside of run method):
return 1;
Using the above code each thread can start only if the previus has stopped? Or I'm wrong?
But if I want that each Thread starts only after the previous has stopped, can I use the > following trick?
This means you have a strictly sequential execution and thus the entire code can be on the same thread. What's the point of starting multiple threads if there is no parallelism?
You can use RetrantLock
private final ReentrantLock lock = new ReentrantLock();
if(toModify[j]==1)
{
lock.lock(); // block until condition holds
try {
getUpdate(methods_list[j],username, password);
} finally {
lock.unlock()
}
}
Also you will need to call join() on thread that is started from getUpdate() method.
Thread thread = new Thread(new Runnable() {
public void run() {
// *** some operations***
}
});
thread.start();
thread.join();

Regarding assigning task to daemon thread

I have one requirement that I want to create a pool of 5 threads and now I want to make 1 thread out of those 5 threads as a daemon thread and when that particular 1 thread becomes as daemon thread , then I want to assign some task to that daemon thread related to any service such that when the java program exits I can check in window task manager that particular daemon thread is still doing that task., Please advise how to achieve that ..! As I am stuck up on this..!
below is my code...
public class StoppingThread extends Thread //extend thread class
{
// public synchronized void run()
//synchronized (this)
private volatile boolean Completed = false;
public void setCompleted() {
Completed = true;
}
public void run()
{
for(int i=0;i<20 && !Completed;++i) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(500);
System.out.print(i +"\n"+ "..");
} catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String... a)
{
StoppingThread x = new StoppingThread();
StoppingThread y = new StoppingThread();
x.start();
x.setName("first");
x.setCompleted(); // Will complete as soon as the latest iteration finishes means bolean variable value is set to true
y.start();
y.setName("second");
}
}
Now in this I want to make Y thread as daemon thread and then want to assign some task to it
Use ShutDownHook. The Thread which you register into the hook will be called when the application ends. You can add all clean up codes(DB,Stream,Context etc..) or any custom feature in this thread run method.
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() { // clean up code like closing streams,DB etc }
});

Categories