I am running the following program in Java (through Eclipse IDE):
package threaddemo;
class Runner extends Thread{
#Override
public void run() {
while(true)
System.out.println("Running in a thread ....");
}
}
public class ThreadClass {
public static void main(String[] args) {
Runner thread1 = new Runner();
thread1.start();
Runner thread2 = new Runner();
thread2.start();
}
}
While the program runs, I am trying to see the thread activity in JVisualVM. I was expecting to see both the threads in green concurrently (i.e. running concurrently), however I see that at any point in time during execution, for a little while any one thread is in the Monitor state, while the other is being executed. After a little while, they switch (the former is executing, while the latter is in Monitor state). How can this be?
Both of your threads are trying to write to System.out. Since writing to PrintStream is synchronized, at every time one of your threads is writing to the stream and another is waiting for the stream to become available.
You would be able to see threads executing at the same time if they performed some activity that does not depend on a shared resource (for example, some computation).
Related
class TestJoinMethod3 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestJoinMethod3 t1=new TestJoinMethod3();
TestJoinMethod3 t2=new TestJoinMethod3();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
t1.start();
t2.start();
t1.setName("Hello");
System.out.println("After changing name of t1:"+t1.getName());
}
}
i got this out put
Output:
Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Hello
running...
but according to my debugging i expected this one
Output:
Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
running...
After changling name of t1:Hello
What mistake i have done in my debugging?
As mentioned here, Threads are meant for executing code/instructions separately and usually up-to the mercy of Scheduler, an Operating System component.
When you say t1.start(), you're asking for a new thread to be started, but it's not guaranteed to run immediately. It goes in to a state called Runnable which makes them eligible for scheduling. Once the Scheduler picks these Runnable threads and allocates CPU to them, then they're actually in Running state. This is actually the time when your code inside run() is executed.
In java, your main thread (in your case the thread executing your main()) will not wait until all the threads it spawned are done executing their code. All threads are usually executed in a call-stack separate from your main method call-stack so the control immediately comes back to main() for executing the remaining the code (in your case , sys-outs). It's possible that by the time, main() ended, Thread t2 is not picked by the Scheduler, that's why you're not seeing 2 Running statements. Perhaps, if you try several times, then you might 2 statements but it's not guaranteed. Like I said earlier, it's up to the scheduler.
Perhaps, if you try to write them to a file, then you might see 2 Running statements (or) you can try using a thread-pool from Executors class which will not shutdown until you explicitly call shutdown(). That another way to experiment with threads without having to create them by ourselves.
Here's an image to help you understand the flow. Every method call becomes a new stack frame (even calls to constructors but I removed them for brevity) in a call-stack executed by a thread. As and when a method is completed, stack frames are removed and finally comes back to main().
PS: Above image is an approximation, it's not an accurate representation of how JVM manages threads.
To make the main thread wait for the threads to run to completion, you can use a lot of thread co-ordination constructs like join(), wait() & notify(), Semaphores & Cyclic Barriers.
join() is the simplest of all but it doesn't scale well when you're dealing with lot of threads.
So if you want your main thread to wait until t1 and t2 are done, you need to explicitly say so by doing something like this
t1.join() // blocks the main method thread until t1 is done
t2.join() // block the main method thread until t2 is done
If you're using join(), then you need to handle InterruptedException. join() also has overloaded method that waits for a specific time instead of waiting indefinitely like the no-arg version.
Threads run independently, you need to synchronize them to get the desired output. What you can do is:
class TestJoinMethod3 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestJoinMethod3 t1=new TestJoinMethod3();
TestJoinMethod3 t2=new TestJoinMethod3();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
t1.start();
t2.start();
try{
t1.join();
t2.join();
}catch(InterruptedException e){
System.out.println("Interrupted");
}
t1.setName("Hello");
System.out.println("After changing name of t1:"+t1.getName());
}
}
i am trying to run two thread Parallel but according to the output they are not looks like parallel.i am new to java and unable to figure out my mistake.
here is my little effort.
Main class code:
public class FirstProgram {
public static void main(String[] args) {
TwoThread tt=new TwoThread();
tt.start();
for(int i=0; i<2; i++) {
System.out.println("Main class Thread");}
}
Second class code
public class TwoThread extends Thread {
public void run() {//
for(int i=0; i<2; i++) {
System.out.println("New Thread");
}
}
}
output
Main class Thread
Main class Thread
Main class Thread
New Thread
New Thread
New Thread
Expecting output
Main class Thread
New Thread
Main class Thread
New Thread
Main class Thread
New Thread
You're starting the second thread correctly¹, and your threads are (potentially) running in parallel. But that doesn't mean that they'll necessarily be scheduled to interleave like that. There's also a bit of thread startup time.
If you made your threads run for longer, you'd see that they are running in parallel.
For instance, on my mid-spec multi-core machine, running 20k loops rather than 3 in each thread showed blocks "Main class Thread" interspersed with blocks of "New Thread". The first block of "Main class Thread" was fairly large, which isn't a surprise because of the startup time for the new thread, and then the blocks of output from the two threads were largish but interwoven. YMMV, though, since thread scheduling can vary.
¹ Although in general, the recommendation is to implement Runnable rather than extend Thread, and then use new Thread(new TwoRunnable()) to create it.
You cannot expect any ordered output from a multithreaded application (until you artificially synchronising/joining your threads).
When you start() a Thread it submitted to the Thread Scheduler.
Thread Scheduler is a part of the JVM that decides which thread should run. There is no guarantee that which Thread will be chosen for execution. The Thread Scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.
If you have multiple cores, both threads can run in parallel (and that's the difference between concurrent and parallel execution). But still it doesn't change the fact that it depends on Thread Scheduler and the execution is unpredictable.
I have Main class with main method. I create two Threads What i noticed that code from main thread executes before created Threads. What i was expecting is to run it simultaneous. Why code from main method executes berofe code from Threads?
Main.class:
public class Main extends Thread {
public static void main(String[] args) {
NewThread thread = new NewThread("Thread1");
NewThread thread2 = new NewThread("Thread2");
for (int i = 0; i <3 ; i++) {
System.out.println("From main thread");
}
thread.start();
thread2.start();
}
}
NewThread.class
public class NewThread extends Thread{
public NewThread(String name) {
this.setName(name);
}
public void run() {
int clientnumber = 1;
while(clientnumber!= 3) {
System.out.println("server sent data to client: " + getName());
clientnumber++;
}
}
}
Output:
From main thread
From main thread
From main thread
server sent data to client: Thread2
server sent data to client: Thread1
server sent data to client: Thread2
server sent data to client: Thread1
Why code from main method executes before code from Threads?
Simply, because it can.
When you start() a thread, either the parent thread or the child thread may be scheduled to run next. Or they may both scheduled simultaneously. Or an entirely different thread may be scheduled.
The Java language and runtime system make no guarantees of thread scheduling order. Furthermore thread scheduling behavior is liable to be different for different execution platforms1; e.g. depending on how many cores you have.
(Why? Because, this is how native thread scheduling works on a typical OS. Java can't fight this and still use native threads. Using user-space threads and thread scheduling has serious performance issues. Sun abandoned that approach decades ago.)
What do you do to solve this?
Don't make assumptions about scheduling, and the order in which threads will execute.
If your application really needs one thread to run before the other, use one of the concurrency primitives or classes to achieve it ... explicitly. (But beware that by forcing one thread to run before another you are reducing the effective concurrency.)
In your example, the problem is basically that your expectations were incorrect. It is no longer a problem once you have adjusted your expectations.
1 - Behavior is likely to be repeatable on a given platform, especially in a small / simple example like yours. But then again, it could change if you ran your test while the system was under heavy load. Remember: No guarantees!
Execution of other threads starts with .start() method - you call this method after loop printing informations to the console in `main.
EDIT: These lines are printed before lines from new threads, because it is likely to be faster to print 3 lines to the console than perform loops in other threads and then print. After edit that you made to the question - to see how all three threads (including thread containing main()) are working in the same time and to see the difference in order of printed lines - I suggest you to try one of the following ways to see the difference:
Try to perform time-consuming operation in main() after starting new threads and before printing to the console in main() (you can think of that operation on your own or try one of these listed in these answers, or
Try to increase number of loops (maybe even to few thousands) with statements printing to the console in each thread - you'll see that all threads work in the same time, or
Simply call Thread.sleep(1000) (or higher number as the argument - it's number of milliseconds that you want the current thread to sleep) in main() after starting new threads and before printing lines from the main().
NewThread thread has to be started before it will start executing. You are starting both threads only after main() has processed the loop. What you want is probably:
new NewThread("Thread1").start();
new NewThread("Thread2").start();
for (int i = 0; i <3 ; i++) {
System.out.println("From main thread");
}
However it's up to JVM and OS to schedule the threads. You still might observer the main() executing first before NewThread gets a chance to run.
I'm trying to write a unit test that requires mulitple threads. However, it seems that the threads just stop part way through execution. Consider the following code:
public class Test {
#org.junit.Test
public void TestThreads() {
new Thread(new Runnable() {
public void run() {
for (int i = 1; i < 1000; i++) System.out.println(i);
}
}).start();
}
}
If I run this unit test, it will generally stop displaying output somewhere between 140-180. If I convert this code into a regular class and run it, it works fine. Does anybody have any idea what I'm missing here?
Thanks,
- Andrew.
You can use Thread.join() to prevent the test from finishing before the new thread has completed its task:
#org.junit.Test
public void TestThreads() throws InterruptedException {
Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 1; i < 1000; i++) System.out.println(i);
}
});
t.start();
t.join();
}
Normally, the JVM will terminate when the last non-daemon thread terminates. You might expect that simply calling t.setDaemon(false) on the thread would prevent the JVM from exiting before the task is finished. However, junit will call System.exit() when the main thread has finished.
As Gus notes in the comments: "you need join() because start() doesn't block".
He's correct that you could also call run() in this minimal example. However, I assume you're starting a thread because you want it to run concurrently with another thread. Calling run() on a Thread is flagged up as a possible mistake by FindBugs - if you're just going to call run(), you'd probably just want to implement Runnable instead of using Thread.
In the TestThread function, JUnit has no way of telling that you spawned a new thread. It reclaims any objects it created in the function as soon as the function ends (last line is reached) and doesn't know about the thread.
For this reason, you see Output from the Thread until it gets killed. If you want to wait for Thread Completion, you can use Thread.join (right after you call Thread.start()) to make it wait for the result or use wait-notify on some object.
Also, found this question: JUnit terminates child threads
It's probably that the parent thread running the test is finishing. If you can avoid it then don't create a new thread in you tests. I would create a new class implementing the runnable and then test that class my simply calling run on that object. You shouldn't need to test thread scheduling as part of your tests. Hopefully the java language dev team have that covered :)
The question is, is it possible to have an external thread or do they have to be internal to the class they run in. If so could someone show me how. (external thread)
A thread, or, more precisely, a thread of execution is something, and the class Thread is something closely related but different, and it seems that you are mixing up these two concepts.
You can think of a thread of execution as a machine that will execute operations sequentially. One way to define and run such a machine is to write a class MyClass with a main() method and call java MyClass.
Another way is to create a new instance of the Thread class and call its method start(). This will create a new thread of execution which will run the code that is in the run() method of the Thread class, which does nothing by default. For this to be useful, you usually override the run method, which is what I think you are calling a thread internal to the class...:
class MyThread extends Thread {
#Override public void run() {
// ... some code ...
}
}
// ...
final Thread t = new MyThread();
t.start();
In this example, after the run() method of the class MyThread returns, the thread of execution associated to that instance of MyThread will terminate (just like when your single-threaded program returns from -- or reaches the end of -- your main() method).
Another possibility is to pass the Thread an instance of a Runnable. Then you separate the 2 concepts: the thread of execution, which is represented by an instance of Thread, will execute the code in the instance of Runnable:
class MyRunnable implements Runnable {
#Override public void run {
// this code will get executed by a thread
}
}
// ...
final MyRunnable r = new MyRunnable();
final Thread t = new Thread(t);
t.start();
This maybe closer to what you call an external thread, although this nomenclature is highly unconventional.
So, you see that there are 2 different, but closely related, concepts here.
Now, in Java you have a way to create a thread of execution that will be waiting for you to give it some code to execute. After it is created, it goes to a pool, and sits there. You submit some code for it to run, and when it finishes, instead of terminating, the thread of execution keeps alive and goes back to that pool. Maybe this is what you are looking for.
To do it, you usually use an ExecutorService. For example:
class MyMainClass {
private static final ExecutorService es = Executors.newFixedThreadPool(10);
public static void main(String... args) {
es.submit(new MyRunnable());
es.submit(new MyRunnable());
es.submit(new MyRunnable());
es.submit(new MyRunnable());
es.submit(new MyRunnable());
}
}
In this example, the pool contains 10 threads of execution. You can submit any amount of instances of Runnable for it, and it will distribute them among the 10 threads. Each call to submit(...) on the ExecutorService returns an instance of Future, which you can use to know if the thread of execution that was running your Runnable did already finish, and if it finished successfully or due to an uncaught exception.
I suggest that you take a look at the javadocs for all the classes I mentioned here: Thread, Runnable, ExecutorService, Executors and Future. There's a lot to learn from that documentation!
As a final note, remember that if you start playing with threads and ExecutorServices, you will get all kinds of headache. You will have to think about situations in which the execution cannot proceed (deadlocks, livelocks), about operations that need to be atomic (ie, incrementing a variable from different threads), memory visibility (ie, if you change the value of a field without "taking care", it can happen that other threads will never notice the change to that field!). Also remember that the JVM won't die until every last non-daemon thread finishes; in other words, the example above will never terminate, even if all the submitted Runnables finish, because the threads of execution in the ExecutorService are still alive!