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();
Related
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.*/
I have thread in my android app which finish its task but still it is not exit , when I run it again I got error that thread is already alive
my thread
Thread mythreads = new Thread()
{
#Override
public void run() {
// do some work
// exit point
}
};
so please how can I stop this even thread finish it code execution , but when I try to run it again it give me error
java.lang.IllegalThreadStateException: Thread already started
I try to stop with it with my threadkill function code but no success
public void killthread(Thread tname){
try {
if (tname.isAlive()) {
Log.d("tag1","Thread is Alive");
tname.interrupt();
tname = null;
}
}catch (Exception e){
e.printStackTrace();
}
}
Thread objects are only meant to be started once. If you need to stop/interrupt a Thread, and then want to start it again, you should create a new instance, and call start() on it:
thread.interrupt();
thread = new YourThreadSubclass();
thread.start();
In your case you are doing Thread mythreads = new Thread() so it shouldn't be a problem at all unless you are explicitly trying to stop it before completion of the excecution.
Creating Anonymous Thread
new Thread()
{
public void run() {
//Your code
}
}.start();
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.
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.
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 }
});