how to run two thread parallel in java - java

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.

Related

If java normal threads don't call "join", does it lead to unknown behavior before finish?

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.

Why code from main method executes before other Threads in java

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.

Regarding Threads and JVisualVM

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).

java external threads (outside the class file it's used)

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!

Multithreading java

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();
}
}

Categories