I have 2 question regarding on Thread, I just want to clarify something. With the below code:
public class MyThread implements Runnable {
Boolean StopThread = false;
Boolean DontLoop = false;
public MyThread(){}
public void Stop(Boolean stopThread){
this.StopThread = stopThread;
}
public void ThreadDontLoop(Boolean dontLoop){
this.DontLoop = dontLoop;
}
public void run(){
if(dontLoop){
while(true){
if(StopThread){
break; //Terminate WhileLoop, This will Stop and destroy the Thread also
}
}
}else{
//Does this mean the Thread will be destroy/terminate after this condition?
}
}
}
In order to Start:
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.start();
In order to Start Thread but Don't Loop
ThreadDontLoop(false);
thread.start();
In order to Stop the Thread
myThread.Stop(true);
Now, According to this LINK, that's how the thread to be stopped.
So my first question is, in the Given code above, what if I call ThreadDontLoop(false); then thread.start();, does this mean the Thread will Start but after the condition, the Thread will be stopped and destroy?
Second question is, Let's say I call thread.start(); then later I call myThread.Stop(true); to stop the WhileLoop and Destroy the Thread.
I didn't follow on how the link is stopped the thread since I will have a different condition, but I believe that the logic on how I would like to stop the Thread is correct?
You need a volatile boolean or the value can be inlined and never appear to change.
in the Given code above, what if I call ThreadDontLoop(false); then thread.start();, does this mean the Thread will Start but after the condition, the Thread will be stopped and destroy?
Yes.
Let's say I call thread.start(); then later I call myThread.Stop(true); to stop the WhileLoop and Destroy the Thread. I didn't follow on how the link is stopped the thread since I will have a different condition, but I believe that the logic on how I would like to stop the Thread is correct?
If you don't have a visibility issue (does the thread see your change) it will stop. In the code you have in the question, most likely the code will be optimised to assume the thread never sees the change.
Related
I have this Question :
Create and run a thread that writes "Hello friends" on screen. The main Thread waits for it only 500 milliseconds. Then run the program again after you give the created Thread lower priority than the main Thread. This time, the main Thread should wait for it 10 milliseconds. Do you notice anything? Why?
I want to know the difference that made by Thread.setPriority(n)
first code and second get the same output
first code
public class Q2 {
public static void main(String[] args) {
Thread2 myThread = new Thread2();
myThread.start();
System.out.println("main thread");
}
}
class Thread2 extends Thread{
#Override
public void run(){
try {
join(500);
System.out.println("Hello Friends from thread2");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
seconde code
public class Q2 {
public static void main(String[] args) {
Thread2 myThread = new Thread2();
myThread.start();
System.out.println("main thread");
}
}
class Thread2 extends Thread{
#Override
public void run(){
try {
setPriority(MIN_PRIORITY);
join(500);
System.out.println("Hello Friends from thread2");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
the main Thread should wait for it 10 milliseconds
That's not what your code does. The join should be in the main thread, not in the newly created thread:
Thread2 myThread = new Thread2();
myThread.start();
myThread.join(10);
I assume the whole idea of this exercise is to see the difference between two threads with different priorities. Giving a thread a lower priority may delay its scheduled execution. When the main thread waits for a smaller duration for the new thread to finish, the outputs of the two threads may interleave since the main thread may continue to reach the System.out before the second thread does.
The documentation of the Thread class explains what a thread priority is:
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority.
In general, don't extend Thread, you should wrap a Runnable instead.
The Thread priority is
just a hint, the OS can and does ignore it if you don't have the right permissions.
It will only matter if you don't have free CPU. If you have free CPU every thread which wants to run can run.
it really won't matter if you are putting your thread to sleep. e.g. a join.
The only difference it could make is when your machine is very busy, it would take a little longer to wake up from the sleep. e.g. instead of taking say 500 to 501 ms to do the join, it might take 510 ms sometimes.
how can I use join method ?
The purpose of join is to wait for another thread to finish up to some time limit. If you join on yourself, this is effectively the same as Thread.sleep I suggest using Thread.sleep instead as this is less confusing.
First, from the documentation for Thread:
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
So when you have two Thread instances, lets say the current one and a new one, you can cause the current thread to wait for the new one to die:
final Thread t = new Thread(() -> System.out.println("Test"));
t.start();
t.join();
So now our current thread (the one creating t) will wait for t to die, then continue. This method makes an asynchronous task synchronous.
Now, what does calling join in a Thread do? Well, it means that the thread will wait for itself to die. This is the same as TimeUnit.MILLISECONDS.sleep().
So what does your code actually do?
Well, main calls the following code:
Thread2 myThread = new Thread2();
myThread.start();
System.out.println("main thread");
There is nothing here that makes main wait for anything, main dies.
Now your Thread2 (terrible name for a class) does the following:
setPriority(MIN_PRIORITY);
join(500);
System.out.println("Hello Friends from thread2");
So it sets its own priority, it then waits for 500 milliseconds for itself to die. Obviously it doesn't die in that time. It then prints.
TL;DR: setPriority does next to nothing in this code
One further note, do not extends Thread, use a Runnable.
I create a thread using
Thread t = new Thread();
t.start();
You start a thread using t.start();
Now how long the thread will be alive?
To what state it will go after X (the answer of above question) seconds?
Thread t = new Thread();
t.start();
public void run(){
System.out.println("Threads");
}
What will happen if the thread has run() method?
A thread created and started exactly as you describe will be alive only for as long as the empty Thread.run() method takes to do nothing and return. When the thread terminates, the t.isAlive() function will return false.
Normally, a thread does something useful and will be alive for as long as the run() method has not returned.
If my thread receives an InterruptedException in a sleep(), how can I tell whether it was caused by a call on its .interrupt() or .notify() method?
The long story:
I have a View() class running in a thread. It should run worker(s) and update the view from time to time. It should also measure the time the worker took. The View() should be interruptable by the application (upon shutdown). The workers should wake up (notify) the thread during sleep when they have finished to measure the time they took. (Without notification, time measured would be rounded up to the next full sleep cycle which isn’t desired.) So an InterruptedException can be triggered by a call on the thread’s .interrupt() or .notify() method. How do I distinguish this inside the catch block?
public class View() implements Runnable {
Long started = null;
Long finished = null;
#Overload
public void run(){
Set<Thread> workers = new HashSet<Thread>();
for(int i = 1; i <= 5; i++){
Thread worker = new Thread(new Worker());
worker.start();
workers.add(worker);
}
started = System.getCurrentTimeMillis();
do{
try{
TimeUnit.SECONDS.sleep(3);
updateView();
}catch(InterruptedException e){
if(--> thread_was_notified <--){
finished = System.getCurrentTimeMillis();
updateView();
}
if(--> thread_was_notified <--){
for(Thread worker : workers)
worker.interrupt();
}
return;
}
}while(true);
}
protected void updateView(){
// …
}
}
I first guessed that InterruptedException would have Subclasses, but there are none directly known subclasses listet in the javadoc. Thread provides .isInterrupted(), but as said here: “By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so.” So I can’t tell from .isInterrupted() either. What’s the clean way to do it?
I have a vegue idea that my code should use Object.wait(), but what’s the waiting object?
The ugly solution:
Instead of having your Workers interrupting the View thread, put a method like this:
public void workedFinished() {
interruptedByWorker = true; // View attribute.
viewThread.interrupt(); // Interrupt the view
}
Then, when you're on your catch, check for the interruptedByWorker boolean. If it is true, it was interrupted by a worker. Otherwise (make sure this is happens), it was interrupted by the shutdown.
The other solution
Instead of interrupting the thread in two different places (which I think it could be confusing an error-prone), you could do the following:
1) Schedule a Runnable to run every 3 seconds using a ScheduledExecutorService to update the view.
2) Have a CountdownLatch that is notified for each Worker that finishes. Please, notice that in your code, the first thread wakes up the View, meaning that the measured time will be only for that thread, it will not wait until the other threads finish.
InterruptedException is only thrown when some thread interrupts you and not thrown when comming out of wait().
So when you are in sleep() or wait() and some other thread decides to interrupt you then Exception will be thrown.
When a thread is in wait() state and notify() is called for it then it will again fetch the lock and resume its working without throwing any exception.
I know that there are a few threads open regarding this topic, but I'm just looking for a VERY ELEMENTARY example of how to use wait() and notify() in Java. By "VERY ELEMENTARY," I mean simply printing something out. Thanks.
EDIT: Here's what I have tried thus far and I get an IllegalMonitorStateException:
public void waiting() {
for(int i = 0; i < 10; i++) {
if(i == 5)
try {
this.wait();
} catch (InterruptedException e) {
}
else
System.out.println(i);
}
System.out.println("notify me now");
this.notify();
}
wait and notify are used in synchronized block while using threads to suspend and resume where left off.
Wait immediately looses the lock, whereas Nofity will leave the lock only when the ending bracket is encountered.
public class Mythread implements Runnable{
public synchronized void goo(){
System.out.println("Before Wait");
wait();
System.out.println("After Wait");
}
public synchronized void foo(){
System.out.println("Before Notify");
notify();
System.out.println("After Notify");
}
public class Test{
public static void main(String[] args){
Thread t = new Thread(new Mythread);
t.start();
}
}
Your IllegalMonitorStateException is due to the fact that you must synchronize on the object before calling wait or notify. So
this.wait
needs to be
synchronized(this) {
this.wait();
}
Your example won't run because you'll never get to the notify call... as soon as your thread hits wait, it will suspend and advance no further. For wait / notify to work, you have to have two threads. One thread suspends when the wait method is invoked, and eventually, the second thread calls synchronized(this) { this.notify() } to cause the first thread to wake up and continue executing below the wait call.
The synchronization is required because you would ordinarily check some condition before waiting, ie,
synchronized(this) {
if(! this.isReady) {
this.wait();
}
}
You need to synchronize to make sure no other thread changes the state of the isReady flag between the line where you check the variable and the line where you wait. So your notify code would
synchronized(this) {
isReady = true;
this.notify();
}
Now the order of the method calls doesn't matter. If you notify first, no thread will wake up, but that's ok, because you aren't going to sleep since isReady = true. If you go to sleep first, isReady = true does nothing, but the notify call wakes up the thread. Finally, the synchronization ensures that you don't check the variable in thread A, then have thread B set the variable and notify (doing nothing), then have thread A go to sleep and never wake up.
Hope that helps.
wait() and notify() are used to synchronise threads: a thread can be told to wait(), and will not continue doing anything until it receives the notify() call.
The basic idea with these functions is that wait() suspends a thread (puts it to sleep), and notify() causes a thread to pick up where it left when it went to sleep.
Take a look at: this or just look up simple prodcuer consumer problem java on google. I am sure you will find something to suit your needs.
See this example on guarded blocks from the oracle java site - it includes a worked example of a simple producer-consumer problem.
Is there a way to check if a Thread object has had start called on it already?
I'm trying to so something like:
if(rt.isAlive() == true)
{
Log.v(TAG, "START RECORD");
rt.recording = true;
}
else
{
Log.v(TAG, "START THREAD/RECORD");
rt.start();
}
where it would start the thread if it's not already running.
Assuming that rt is a Thread, just check rt.isAlive().
Alternatively, just use a boolean flag and set it to true right before you start your thread.
I would actually prefer the boolean approach so there is no way that the main thread could start the other thread twice - there may be a short delay until your Thread is up and running, and if your main thread tries to start the thread twice in quick succession, it may get a "false" negative on rt.isAlive().
I've used this approach with success:
if ( mythread.getState() == Thead.State.NEW )
//then we have a brand new thread not started yet, lets start it
mythread.start();
else
//it is running already compensate
If you called start on it, and it is running, you will get an IllegalThreadStateException. Catching that is one way to know.
Another option is to extend Thread and add a boolean where you keep track of whether or not your Thread has been started. You can override the start method of Thread to check the boolean before calling up to super.start().
You should be very careful when using threads in Android though. Make sure you understand the lifecycle of the component that is starting it. Also, you should consider some of the helper classes like Handler and AsyncTask instead of directly spawning threads.
Call this method by passing a thread. It will check the thread is alive or not, every 500 milliseconds with start delay of 500 milliseconds (you can use your custom values). I use this method often.
void threadAliveChecker(final Thread thread) {
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (!thread.isAlive()) {
// do your work after thread finish
runOnUiThread(new Runnable() {
#Override
public void run() {
// do the ui work here
}
});
timer.cancel();
}else {
// do work when thread is running like show progress bar
}
}
}, 500, 500); // first is delay, second is period
}
Example:
Thread thread = new Thread(myRunnable);
thread.start();
threadIsAliveChecker(thread);
This method will let us know when the thread is finished doing its work.