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.
Related
Normal java threads, not daemon threads, seem to execute till end, then main thread finishes, like this:
public static void main(String[] args) {
for(int i = 0; i < 3; ++i){
new Thread(new Runnable(){
#Override
public void run() {
try {
Thread.sleep(2000);
System.out.println("Does this still print?");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
// Java normal threads don't have to call join, they'll still wait to finish.
System.out.println("Main thread start");
}
It will print:
Main thread start
i = 2
i = 0
i = 1
Does this still print?
Does this still print?
Does this still print?
What I saw here is, Java normal threads don't have to call join() and their holder still wait for them to finish. Not sure if my program is too simple to encounter any undefined behavior, could you kindly give some hints when should we use join()?
Thanks.
t.join() does not do anything to thread t in Java. All it does is not return until thread t has finished.
A Java program's main() thread does not wait for any other thread to finish after main() returns. It just ends, and any other non-daemon threads keep running.
Java is not like Go. In Go the program continues only as long as the main thread is alive, in Java any living nondaemon thread keeps the jvm around. In your code the main thread kicks off other threads and then dies. The new threads run to completion even though the main thread is long gone.
For "undefined behavior" I'm guessing you mean data races, or memory visibility issues, where you can't rely on one thing happening before another (for races) or on a value being visible across threads (for vidibility). Calling join does create a happens-before edge. So does calling println (since it acquires a lock). The Java language spec has a list of things that create a happens-before edge.
Calling get on a Future blocks until the future is done similar to how calling join on a Thread blocks until the thread is finished. If you use higher level constructs than just threads, whether it's executor services, CompletableFuture, reactive libraries, actor systems, or other concurrency models, then those are to different extents shielding you from the Thread api and you don't need join so much.
My task is to create x Threads, and in some way to use MethodA and B, and synchronize them, and to catch some Exception in the end.
I know this is not a really good description of the task, but this is how I got the task.
So the question is, would this code do, what the task is asking for?
Are these Threads synchronized correctly or not?
public class Test2{
public static synchronized void doActionA(){
System.out.println("Hi");
}
public static synchronized void doActionB(){
System.out.println("Hello");
}
public static void main(String[] args) {
for(int i = 0; i < 10000; ++i){
try{
new Thread(() -> {
doActionA();
doActionB();
}).start();
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println(":)");
}
}
}
}
This is mostly useless, yeah.
You have 10000 threads. Each thread is going to perform the following task pattern:
NB: Take the object "Test2.class" (the instance of java.lang.Class that represents the Test2 class; there is only one such object in the entire VM loaded. We shall call this 'the locker'.
Check the locker object for its 'monitor' thread. If it is unset, set yourself as the monitor thread of the locker and continue. (and do all that atomically). If not, freeze the thread until the 'monitor' is null again, and then compete with the 9999 other threads that want to set it; only one of the 9999 wins, sets itself as the monitor, and continues. The remainining 9998 will freeze and wait another round.
Execute doActionA. All the while, 9999 threads are twiddling thumbs.
Relinquish the locker (unset yourself as the monitor of the locker). 9999 other threads all fly in to set themselves as monitor. Only one of those will 'win'.
Acquire the lock again (set yourself as the monitor of the locker if it is currently unset; otherwise, freeze and wait until it is available.. and do that atomically). Depending on the JVM implementation, this thread may in fact 'win', and take the monitor riiight back, beating the other 9999 threads.
Execute doActionB. During this job, 9999 threads are twiddling thumbs doing absolutely nothing whatsoever. Just waiting around.
Relinquish the monitor and exit. Pfew. 9999 more to go.
As you can tell, this pattern most likely means this code runs as fast as just:
for (int i = 0; i < 10000; i++) {
doActionA();
doActionB();
}
except the above most likely runs FAR faster, as your example first allocates 1.25 gigabytes worth of memory just to store stacks (each thread needs a stack, and here's praying your stacks are 'just' 128k large, they are often larger), and wastes a ton of time juggling thread states for pretty much no purpose.
This is not how you thread things.
Are these Threads synchronized correctly or not?
"Synchronized" in what way? "Synchronized" for what purpose?
It's "correct" if the program is guaranteed to do what you want it to do. What do you want this program to do?
What it will do is, it will print print ten thousand complete lines of "Hi", and it will print ten thousand complete lines of "Hello", and it will print them in no particular order. The reason each line will be complete is that the System.out object uses synchronization to ensure that at most one thread at a time can execute println(...). The reason why the lines will be printed in no particular order is, there isn't any other synchronization between the threads in the program.
This is the main part of your task:
catch some Exception in the end.
The question is: would this code do what the task is asking for?
No, becasue exception happened inside a thread can not be caught outside of the thread like this, read the following question for more information:
How to catch an Exception from a thread
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.
For the below program different outputs are coming when running and debugging on eclipse.
public class MyClass implements Runnable {
public static void main (String[] args) throws Exception {
Thread t = new Thread(new MyClass());
t.start();
System.out.print("Started");
t.join();
System.out.print("Complete");
}
public void run() {
for (int i = 0; i < 4; i++) {
System.out.print(i);
}
}
}
When running this as java application the OUTPUT is
Started0123Complete
When checking in Debug Mode OUTPUT is
0123StartedComplete
Can someone help on this? is it because of two threads? main thread and the thread which starts with t.start().If yes then why main thread execution is taking more priority to complete first?
Thanks
The order in which the string "Started" and the integers are printed out is undefined by definition. After you call start, there is no guarantee that the code in the run method will be executed before or after any other statement that appears before the call to join. This is the nature of multithreaded applications.
The fact that you see a certain output in debug mode vs run mode is probably purely accidental and might change if you run your code many times or on different platforms/versions of the JVM. If you need deterministic order in this case, the only way you can achieve it is to print a string before calling start or introduce some other sort of semaphore to force the thread to wait for the main thread or viceversa.
It's coincidence. You can't control the thread scheduler.
However, in a debug environment, the debugger plugs into your code to inspect values and execution. This inspection increases the amount of work done per thread time slice.
For example, in a regular run, the main thread may only need 1 time slice to create the new thread object, start it, and print the Started message. Then a context switch would occur and the second thread would get a chance to work. In a debug run, the main thread would only have enough time to create the new thread object and start the corresponding thread. Then the context switch would occur and the other thread would do its thing.
It is not related to being in debug mode or not.
There is no guarantee of when this gets executed
System.out.print("Started"); //this is in the main thread
compared to
for (int i = 0; i < 4; i++) { // this is in the started thread
System.out.print(i);
}
It can even be
01Started23Complete
Yes, Its because of 2 threads But the output is unpredictable.
No, the main thread doesn't get high priority because its MAIN.
you can't say any particular interleaved execution in multithreads.
In Debug, my guess is you put a break point for main thread so it waits and in the mean time the other thread might have executed.
In both (Run / Debug) the mode output will be
Started0123Complete
You are seeing result 0123StartedComplete, because you must be having debug point inside main thread code, that’s why.
If you want to understand better, then move the run() method to inside MyClass and put debugger point inside run method now you will see it is printing as Started0123Complete.
Internally, Main Thread is creating subthread “t” and when t.start() is being called it is waiting to capture the monitor for thread execution (i.e. run()) and when you are adding debug statement in main thread, sub-thread is entering into monitor and run method is executing and once it completed, main thread is starting again.
I'm trying to figure out how to multithread in java. Right now, my program works fine with no concurrency but I want to implement multithreading to help speed it along.
The program runs several objects of a separate sub class and 50% of the time evaluation for each of those objects is spent in a process which only utilizes one core rather than the 8 available. These objects are completely independent of one another until but are used as inputs in the program.
I am trying to multithread this by having the subclass implement Runnable and then have my program use a thread for each such object. Would this be the correct way?
However, how are threads in java handeled? Would I need to dispose of the threads after each run? How does join work?
thanks
Don't manage threads manually, take a look at executors and thread pools in java
You're pretty much on track. You'll create a Thread object
Runnable r = new MyClassImplementingRunnable();
Thread t = new Thread(p);
t.start();
t.join(); // wait for thread to die
The Thread object is garbage collected like any other object, the thread itself dies when the run method completes. The key thing is that your Runnable's run method really must guarantee to return, your design cannot depend on being able to kill thread from the outside.
If you are going to have lots of threads you need to wait for them all to finish, so you can either keep a collection of the threads you've started and then use t.join( smallNumberOfMillis) to see which of them has finished. That's a little inefficient so there are other techniques for allowing threads to communicate with each other, I'd suggest reading this article about them.
#denis also mentions that the Executor and related classes provides a nicer abstraction above Threads. If you have an interest in learning the background then manually managing Threads is interesting. If you just want to get the job done, follow Denis' suggestion.
Take a look at http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html
The constructor takes the number of threads you want. In this case the same as your number of cores.
ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(8);
List<Future> futures = new ArrayList<Future>();
foreach(...something...)
futures.add(s.submit(new MyCallable()));
foreach(Future f : futures)
f.get(); // Result of computation
System.out.println("Done");
This is a good way to start multithreading.
public class ThreadExample {
public static void main(String[] args) {
//Main thread
System.out.println("Main thread");
new Thread(new Runnable() {
#Override
public void run() {
//This thread is independent of the main thread
System.out.println("Inner Thread");
}
}).start();
}
}