Is there a way for a thread that starts a new thread to wait until the thread it started has stopped? I was thinking about using locked, but then if the thread crashes, the lock will never get release.
so when my program calls
cTurnCardOvrerConnection thread = new cTurnCardOvrerConnection("thread3", connection, mPlayerList, mPlayersMessages, lBoard);
will it wait until the thread is finished?
mPlayerList.WaitForAllPlayers();
do
{
do
{
r=GetClient();
switch(r)
{
case 0: return; // exitvon a very bad error
}
} while(r==2); // loop if it was a timeout wait for this thread to terminate.
cTurnCardOvrerConnection thread = new cTurnCardOvrerConnection("thread3", connection, mPlayerList, mPlayersMessages, lBoard);
if ( CheckTimeStamp())
break;
} while( mPlayerList.AllPlayersFinished()==false);
you can just use Thread.join().
of course, if the primary thread is just launching the secondary thread and then waiting for it to finish, there's really no use for the secondary thread (just do the work on the primary thread).
Try using a CountDownLatch.
Related
I want to pause the main thread until the other thread finishes.
I tried CountDownLatch and semaphore. but none of them worked. I got the same error for both.
Caused by: java.lang.IllegalMonitorStateException: object not locked by thread before wait()
Code
public void testCountDownLatch(){
final CountDownLatch countDownLatch = new CountDownLatch(1);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2000);
countDownLatch.countDown();
//Toast.makeText(MainActivity.this, "Latch Released", Toast.LENGTH_SHORT).show();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
try {
countDownLatch.wait();
Toast.makeText(this, "Yes! I am free now", Toast.LENGTH_SHORT).show();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
I tried to search for a few hours and was able to understand the cause of the error (wait() won't know if the countdown() gets called before it, in that case it would wait forever) but I couldn't able to understand how to fix it:(
You are calling the wrong method. You need to use await() instead of wait().
wait() is a method from Object and that method requires to synchronize over that object. Other synchronizers are normally preferred over Object#wait. Objects locked with Object#wait can be woken up with Object#notify or Object#notifyAll.
await() is a method of CountDownLatch and it waits for the CountDownLatch to count down (using CountDownLatch#countDown) to 0.
If you use Semaphore (basically the opposite of CountDownLatch), you can aquire (increase the count of the semaphore by 1 if its limit has not been reached yet) it with Semaphore#aquire and release (decrese the count of the semaphore) with Semaphore#release.
Aside from that, it seems like you are developing an Android app. You should never block the main thread of an Android application (or the UI thread of any graphical application) as this will block your UI and result in Application not responding notices. Blocking the UI (thread) means that your app will not respond to any UI events (like the user clivking on a button). If you need to do blocking stuff, you should do that in a background/worker thread. You should also refrain from doing IO operations in the main thread for that reason (android even blocks network operations in the main thread).
You are using the wrong method. You should call await, not wait. See CountDownLatch for example code.
1.The thread should start
2.It should be await and not wait.
I'm developing an Android App in Java. I used a lot of library: firebase crashlytics, SQLCipher, ButterKnife etc.. The problem is: when I run the app from Android Studio, I notice the app still remain active as process, even if I close all activities. I know that there are some thread that works on background.. but I don't know how to check which thread is active, and more important, what does it do. Any idea about?
You can get what state a thread is in by using the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time.
NEW A Fresh thread that has not yet started to execute.
RUNNABLE A thread that is executing in the Java virtual machine.
BLOCKED A thread that is blocked waiting for a monitor lock.
WAITING A thread that is wating to be notified by another thread.
TIMED_WAITING A thread that is wating to be notified by another thread for a specific amount of time.
TERMINATED A thread whos run method has ended.
Thread t = new Thread();
Thread.State e = t.getState();
Thread.State[] ts = e.values();
for(int i = 0; i < ts.length; i++){
System.out.println(ts[i]);
}
To kill the thread , u can do this :
myService.getThread().interrupt();
NOTE : the method Thread.stop() is deprecated
EDIT : : try this
public void stopThread(){
if(myService.getThread()!=null){
myService.getThread().interrupt();
myService.setThread(null);
}
}
My code:
package multithreading;
public class JoinT1T2T3 extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println("Daemon thread is running");
}
else
{
System.out.println("Slave thread");
}
}
public static void main(String args[])
{
Thread t=new Thread();
t.setDaemon(true);
T1 thread1=new T1();
T2 thread2=new T2();
T3 thread3=new T3();
System.out.println("First Thread name is::: "+thread1.getName());
thread1.setName("XXXXXXXXXX");
System.out.println("First Thread After changing name::: "+thread1.getName());
System.out.println("First thread's id is :::"+thread1.getId());
thread1.start();
try
{
thread1.join(3000);
}
catch(Exception e)
{
System.out.println("-----------");
}
//thread2.start();
thread2.start();
thread3.start();
}
}
Why is my daemon not reachable? Please provide me an explanation and code.
T1,T2,T3 are three different classes. The main method is also the run method. I created a new thread instance. Still getting "code not reachable". Which is if{} else{} in run method.
You are getting the "not reachable" error because JoinT1T2T3#run() is never called anywhere.
To Reach JoinT1T2T3#run()
In order for a run() method to be called, an object of its containing class should be explicitly passed to a Thread at construction-time using Thread#(Runnable). For example:
Thread t = new Thread(new JoinT1T2T3());
Now, Thread t will call JoinT1T2T3#run() whenever it starts.
To Run t
Even if t is a daemon, it must still be start()'ed just like any other Thread, or else it will not run. (and thus JoinT1T2T3#run() will never be called) So you need to do this:
Thread t = new Thread(new JoinT1T2T3());
t.setDaemon(true);
t.start();
explaining "daemon" threads
Generally speaking, in Java the only functional difference between a deamon Thread and a non-daemon Thread is that "the Java Virtual Machine exits when the only threads running are all daemon threads" (source). Other than that, a daemon Thread behaves exactly like a non-daemon Thread, syntax and all. It must still be constructed with a Runnable and start()'ed, just like any other Thread.
However, because a daemon thread may be abruptly terminated when the JVM exits, daemons should be used sparingly. In particular, daemons should not be used for any I/O or resource cleanup. "Normal" guarantees about stuff like finally blocks and stack unwinding don't necessarily apply to daemon threads--if the JVM decides to exit, all daemons are immediately abandoned. (source)
Java daemons should be used only for background housekeeping, bookkeeping, metrics, non-critical monitoring, etc.
I have an activity running, of course, on UI thread and there is another thread running in background and communicating with activity using Handler post method(through looper).
When screen is turned of or application is hidden it continues to work.
So I need to stop this thread in onPause method and wake it up in onResume mehtod.
In my thread I have condition to pause it or to stop.
How to can I put thread to sleep in onPause method. And wake it up after activity is again in foreground.
I can do it with one object using monitor calling wait method and than notify on this object.
But is it good approach ? Or there is another way to do this elegantly.
Sounds like a good place to use a turnstile. Initialize a Semaphore with one permit:
Semaphore turnstile = new Semaphore(1);
Make your background activity periodically pass through the turnstile like so:
turnstile.acquire();
turnstile.release();
When the foreground thread wants the background thread to pause at the turnstile, it can lock the turnstile:
turnstile.acquire();
And when the foreground thread wants that background thread to start working again, it can unlock the turnstile():
turnstile.release();
Good software engineering practice would be to wrap the whole thing up in a Turnstile class with appropriately named methods for the foreground and background threads to call. I'll leave that as an exercise for the reader.
Android suggests using services for long term background tasks, but if you're just opening a new thread that is tied to your Android lifecycle, I don't think it would be bad to use a monitor and call wait/notify. Can you be more specific with what you are doing?
This is an overview of how I would stop and resume a stopped thread. (You may want to implement runnable in yours)
class ThreadDemo extends Thread {
private Object monitor; //This is the monitor
private boolean keepRunning = true;
private Thread t;
ThreadDemo(){
System.out.println("Creating thread");
}
public void callinOnResume(){
synchronized(monitor){
monitor.notify();
}
}
public void callinOnPause(){
try {
synchronized(monitor){
System.out.println(threadName + "Waiting");
monitor.wait();
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted " + e.toString());
}
}
public void run() {
System.out.println("Starting to loop.");
while (keepRunning) {
//stuff
}
System.out.println("Done looping.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
It is a bad practice to stop/resume a thread outside that thread. The thread must decide itself when to run and when to stop. As a result, the background thread should check periodically if its work is still needed, and the client (foreground) thread should issue some signals about that.
One way to issue signals is to form that signals as jobs of type Runnable and then execute them on a thread pool. So when the activity sleeps, it just does not issue signals.
The main problem when a background thread wants to update the UI is that the target Activity can be closed (or in the process of recreation) and the updating task fails. The AcyncTask class does not solve this problem. A correct solution is published at my Github workspace. But before to use this or another solution, think twice if you really need a background thread. The best way is not to use background thread at all, making all UI updates directly on the UI thread. Of course, if updates are taken from the network, then a background thread must be used.
I have 3 threads called T1 , T2 and T3 and also i have 3 daemon threads like dt1, dt2 and dt3.
I want to (assign) provide a service dt1 to thread T1 , dt2 to thread T2 and dt3 to thread T3.
when threads T1,T2 and T3 complete their runnable task it's related daemon thread also got closed internally.
Can any one please tell me how to do it in java using thread daemon concept?
"Daemon thread" is not a concept - it's just a feature of Java threads. When a JVM is terminating, it waits for non-daemon threads to terminate by themselves. On the contrary, daemon threads just get terminated no matter what they're doing.
Leaving that behind, one idea might be to establish a "shutdown" flag inside your "daemon" thread. When the non-daemon thread terminates, it could set that flag to true. The daemon thread would check the flag and terminate once it's true. Remember to synchronize that mechanism properly, e.g. by using the volatile keyword.
So, if I understand your question correctly, you want each 'work thread' T1..T3 to have its own background thread (dt1…dt3) doing some co-processing, and you want the background thread to exit when your main thread exits, yes? You could do something like this:
Make each 'main thread T1… a Runnable that looks like this, so that when you launch your T1, it launches its own dt1, and then asks it to shutdown (via interrupt()) when it finishes.
#Override
public void run() {
ExecutorService e = Executors.newSingleThreadExecutor();
Runnable r = new Runnable() {
#Override
public void run() {
// this is your deamon thread
boolean done = false;
while (!done && !Thread.currentThread().isInterrupted()){
// Do your background deamon stuff here.
//
// Try not to use blocking, uninterruptible methods.
//
/* If you call a method that throws an interrupted exception,
* you need to catch that exception and ignore it (or set done true,)
* so the loop will terminate. If you have other exit conditions,
* just set done=true in this body */
}
}
};
e.execute(r); // launch your daemon thread
try {
// do your main stuff here
}
finally {
e.shutdownNow(); // this will 'interrupt' your daemon thread when run() exits.
}
}