class cc extends Thread {
cc(String s) {
super(s);
}
}
class mainn {
public static void main (String args[]) {
cc t1 = new cc("first");
t1.start();
}
}
Question: Is the thread born
at this point --> cc t1 = new cc("first");
or is it born and started at this point --> t1.start();?
"Born" is not a formal term that I've seen before in Java, relating to threads.
The Thread object is constructed/instantiated/created when you call new cc("first").
The thread itself is started when you call t1.start(). It still exists before then, but is not running, and will not be scheduled by the operating system.
(P.S. Java naming conventions are that class names start with capitals - it is surprisingly confusing to read code that violates this. new cc(...) jumps out at me as somehow wrong.)
Thread is born at this point ?--> cc t1 = new cc("first");
At this point thread is in New state which is not alive
t1.start();
Here your thread is alive but may be in Running/Runnable state.
Refer below Java Doc for all States.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.State.html
Example
public static void main(String[] args) {
Thread t1=new Thread(new Runnable() {
#Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("running");
}
}
});
System.out.println(t1.isAlive());
t1.start();
System.out.println(t1.isAlive());
}
Which prints :
false
true
running
If your word "born" creation of new thread object, then it is when you call
new cc("first")
But a thread process will be forked only you start a thread using
t1.start()
and it is when actually ready to run in path of execution from the calling thread.
- At this line cc t1 = new cc("first"); The Thread Object will come into existence.
- At this line t1.start() the toe (thread of Execution) will be created and assigned a Runtime Stack.
Poorly written question but the answer is that it is born at t1.start(); stage.
Related
I'm new to Java multi threading and little confused with how Java join and wait works.
I have the following example
public class Main {
private static int counter;
static class RunnableThread implements Runnable {
private static final String PREFIX = "RT-";
public RunnableThread() {
}
#Override
public void run() {
counter++;
System.out.println(PREFIX+counter);
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread rt = new Thread(new RunnableThread());
//Thread tt = new TradThread();
rt.start();
//tt.start();
try {
rt.wait();
} catch (InterruptedException e1) {
System.out.println("Main thread wait is interrupted");
e1.printStackTrace();
}
System.out.println("MT-"+counter);
}
}
It throws IllegalMonitorStateException as the main thread doesn't hold any monitor. Now in the same code if I change rt.wait() to rt.join() it works.
When I see how join is implemented it looks like it calls the wait() method. Now how is the call to wait from inside the join valid?
I would assume The Main thread when it calls rt.join() the code in the join method is being executed by the Main thread itself.
Please help me to understand this.
Thanks
Thread.join() and Object.wait() are very different.
t.join()
Join current thread where you are behind thread t. So, current thread will not run until thread t finishes its work.
o.wait()
Release the lock of object o and pause current thread. So, current thread will not run until it obtains the lock of object o again by o.notify() or o.notifyAll() from other thread.
Note: you must have obtained the lock of object o before invoking this method.
Technically, in the join code, we have:
wait(0);
...
wait(delay);
in this case, this is the same as calling this.wait(). So to answer the question, the wait function being called is the object referenced by rt wait method.
In my Java program, I will launch two Threads simultaneously. I want for my program to join() on either one of two threads's completion without waiting for both threads to complete. In other words, if thread A finishes before thread B, I want the main thread to join thread A and resume the main thread without waiting for Thread B to finish and vice versa.
Which of those Java classes that allows me to do this?
One solution to accomplish that is with a CountDownLatch, by having the main thread wait for its count to reach zero, and having the two threads each decrease the count (the initial value of the count would be 1 in this case).
public static void main(String[] atrgs){
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
t1.start();
t2.start();
while(t1.isAlive()&&t2.isAlive()){
}
System.out.println("main resumes");
}
Actually, any class in Java allows you to do that since an object of any class can be used as a monitor for waiting a notification. Just create an object, call wait() on it and make your threads notify on this object when finished:
private class Foo implements Runnable {
private final int id;
private final Object monitor;
public Foo(int id, Object monitor) {
this.id = id;
this.monitor = monitor;
}
#Override
public void run() {
try {
Thread.sleep((long)(Math.random() * 10000));
} catch (InterruptedException e) {
}
System.out.println(id + " finished");
synchronized (monitor) {
monitor.notify();
}
}
}
public static void main(String[] args) throws InterruptedException {
final Object monitor = new Object();
synchronized (monitor) {
new Thread(new Foo(1, monitor)).start();
new Thread(new Foo(2, monitor)).start();
System.out.println("Main goes to sleep");
monitor.wait();
}
System.out.println("Main is running");
}
The first notification will unblock the main thread and it will continue running.
I would say that this is a classic solution for your problem, though the solution that #AR.3 suggested will be less wordy and will surely work. I just wanted to show that even a simple monitor object is enough to do what you want.
I wrote following Code :
public class ThreadDemo implements Runnable
{
private Thread t ;
private String threadName;
ThreadDemo(String threadName)
{
this.t = new Thread(this,threadName);
t.start();
}
public void run()
{
System.out.println("New thread has been started!!!" + t.getName());
}
public static void main(String args[])
{
new ThreadDemo("Thread-1");
Thread t = Thread.currentThread();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
new ThreadDemo("Thread-2");
}
}
So i have putted the join method on main thread . When i run it ,its execution never end.
Why it is so ? Why main thread doesn't end ? why it's running for infinite time.
The join() method waits for the thread that you call it on to finish. In your code, you are calling join() on the current thread - that is the same thread as you are calling it from. The main thread is now going to wait for itself to finish. That never happens, because it's waiting on itself...
You should not join the main thread, but the thread that you started instead.
ThreadDemo demo = new ThreadDemo("Thread-1");
try {
demo.t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Just another perspective to this code....
This code will hang even if you do not initialize the ThreadDemo objects
within the main program.
In short all this code can be reduced to saying the following statement,
Thread.currentThread().join() will never return.
I am studying the Threads in java.
I just want a simple example which explains the use of join() in Thread. I have seen this link..
Understanding join() method example
But still not able to understand the concept.
Can anybody explain me the concept of using the join() in Thread.
Any explanation retlated to this will be very helpful to me.
Thanks.
The simplest explanation I can come up is that join makes the caller thread wait for the completion of specified thread.
Say if you have a "main thread" and "thread A", if from the main thread you call A.join(), the main thread will wait until thread A finishes.
The java se manual page about concurrency should help you here: http://docs.oracle.com/javase/tutorial/essential/concurrency/join.html
Thread.join() causes the current thread to wait for the thread you call join() on to die before it resumes execution.
Thread.join() blocks (does not return) until the thread you joined on has finished.
This is not the only way to wait for a thread to finish, but it is the most CPU-usage friendly way. Imagine if you had a loop like this (pseudocode):
while(!thread.isAlive())
{
Sleep(1);
}
This supposedly does the same thing... but, 1000 times per second, it will wake up, check the variable and go back to sleep. This means 1000 context switches (which are expensive) and the program will be slower as a result. This is called 'spinlocking' or 'busywaiting' and is frowned upon in programming as it consumes CPU for no reason.
I did some experiment and here is the result: 1. first started thread t3. 2. started t1 then 3. created t2 and t2 joinned the running thread t1.
By definition, t2 should wait for t1 to die and then it should start.
Observation: I called wait on t1, so t1 is paused but not died but I see then t2 is started why ?
public class TestThreadJoin {
public static void main(String[] args) {
final Thread t3 = new Thread(new Runnable() {
public void run() {
System.out.println("R3");
}
});
t3.start();
final Thread t1 = new Thread(new Runnable() {
public void run() {
System.out.println("R1 before");
try {
perform();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("R1 after");
}
private void perform() throws InterruptedException {
synchronized(this){
wait(5000);
}
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
public void run() {
System.out.println("R2");
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t2.start();
}
}
I have an example that seems strange to me.
public class Join {
public static void main(String[] args) {
Thread t1 = new Thread(
new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
);
Thread t2 = new Thread(t1);
t1.setName("t1");
t2.setName("t2");
t1.start();
try {t1.join();} catch (InterruptedException ie) {}
t2.start();
}
}
We'll see printed only t1.
If we'll comment "t1.join", we'll se the expected output (t1 t2).
Why ?
The second thread is created incorrectly:
Thread t2 = new Thread(t1);
I can't support it by documentation, but in the source code of Thread.run() I see:
if (target != null) {
target.run();
}
Where target is Runnable instance. When the Thread is done, it clears the target variable:
private void exit() {
//...
target = null;
This means that when the first thread is done (join() method) it clears the target and the second thread does nothing. When join() is removed, both access the same target of t1 (race condition).
TL;DR
Never create a thread using another thread instance (even though it implements Runnable). Instead create a separate Runnable and pass it:
final Runnable run = new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName());
}
};
Thread t1 = new Thread(run, "t1");
Thread t2 = new Thread(run, "t2"); //new Thread(t1, "t2"); is incorrect!
t1.start();
t2.start();
You don't need any join()s here, by default these are non-daemon threads.
See also
Java Threading Basics (discussion on #2)
Add before t2.start();:
System.out.println("t1 is alive: " + t1.isAlive());
If main thread is waiting for t1 to die then t2.start() can not run t1's run method. Otherwise, without waiting for t1 to die, t2 can run t1's run method.
This is because main thread waits for t1 to die when you call t1.join().
And when you do this
Thread t2 = new Thread(t1);
you are passing t1 as target object whose run method is called.