unwanted output in multithreading - java

class mythread implements Runnable {
Thread t1;
String name = "";
public mythread(String thname) {
name = thname;
t1= new Thread(this, name);
System.out.println(t1);
t1.start();
System.out.println(t1.getName());
}
#Override
public void run() {
for (int i=5;i>0;i--){
try {
System.out.println(Thread.currentThread());
System.out.println("child Thread" + i);
Thread.sleep(2000);
} catch(InterruptedException e){
System.out.println("Child Thread Interrupted");
}
}
}
}
public class Mainthread {
public static void main(String[] args) {
mythread m1 = new mythread("Rohan");
mythread m2 = new mythread("Jain");
try {
for(int i=5;i>0;i--){
System.out.println("Main Thread" + i);
Thread.sleep(2000);
}
} catch(InterruptedException e){
System.out.println("Main Thread Interrupted");
}
}
}
The output is:
Thread[Rohan,5,main]
Rohan
Thread[Jain,5,main]
Thread[Rohan,5,main]
child Thread5
Jain
Main Thread5
Thread[Jain,5,main]
child Thread5
Main Thread4
Thread[Rohan,5,main]
child Thread4
Thread[Jain,5,main]
child Thread4
Main Thread3
Thread[Rohan,5,main]
child Thread3
Thread[Jain,5,main]
child Thread3
Main Thread2
Thread[Jain,5,main]
Thread[Rohan,5,main]
child Thread2
child Thread2
Thread[Rohan,5,main]
child Thread1
Thread[Jain,5,main]
child Thread1
Main Thread1
but the output i want is like first it should print the 5 in thread "rohan" then 5 in thread in "jain" then 5 in thread "main" and so on...please help..!!!!!!

These sort of questions really confuse me. The whole point of threads is that they run asynchronously in parallel so we get better performance. The order that threads run cannot be predicted due to hardware, race-conditions, time-slicing randomness, and other factors. Anyone who is asking about specific order of output in a threaded program should not be using threads at all.
Here are similar answers to the same question:
These three threads don't take turns when using Thread.yield()?
How can I get my threaded program to print specific output
why output comes different everytime instead of synchronized block
Multi threaded Hello World

You may want to use locks on a single object to control the sequencing. Please refer Java Thread Locks tutorial for further details.

Threads are given processor time or scheduled at the OS level. So your program doesn't have direct control over the times when instructions are executed across its own threads. So there is now guarantee of order. There are a handful of OS specific variables that go into scheduling.
If you want to guarantee order across threads than your threads need to communicate that. There are a handful of ways to do this. Most commonly programmers use a mutex; which is also called a lock.

Related

Is there any order for Java main thread and user created thread execution?

public class SimpleThreads {
// Display a message, preceded by the name of the current thread
static void threadMessage(String message) {
String threadName = Thread.currentThread().getName();
System.out.format("%s: %s%n", threadName, message);
}
private static class MessageLoop implements Runnable {
public void run() {
String importantInfo[] = { "Mares eat oats", "Does eat oats","Little lambs eat ivy", "A kid will eat ivy too" };
try {
for (int i = 0; i < importantInfo.length; i++) {
threadMessage(importantInfo[i]);
}
} catch (Exception e) {
threadMessage("I wasn't done!");
}
}
}
public static void main(String args[]) throws InterruptedException {
threadMessage("Starting MessageLoop thread");
Thread t = new Thread(new MessageLoop());
t.start();
threadMessage("Waiting for MessageLoop thread to finish");
}
}
OUTPUT
main: Starting MessageLoop thread
main: Waiting for MessageLoop thread to finish
Thread-0: Mares eat oats
Thread-0: Does eat oats
Thread-0: Little lambs eat ivy
Thread-0: A kid will eat ivy too
Here at first the main thread printed the message 'main: Starting MessageLoop thread'. After that I started Thread-0 OR MessageLoop thread.
Thread t = new Thread(new MessageLoop());
t.start();
But before starting/printing Thread-0 messages its printing 'main' thread message 'main: Waiting for MessageLoop thread to finish' and Thread-0 was executed after that only. Why ?
That behavior is normal and must be expected, although you can't count on it either way.
You seem to expect the main thread to wait for the second thread to be running. This, however, is not the case with your code. The point of starting a second thread is concurrent execution, implying that that you can't count on the sequence of execution just because the statements in code are sequential.
If you want the main thread to wait for the other thread to execute, then you need to synchronize them. This, however, defeats the purpose of starting the second thread in your case. If you wanted main thread to wait for second thread, you could then just call the method without starting the second thread.
Googling "java concurrency" led to, among other pages, this one. That doc explains a lot of these concepts.
Because invoking start() on a thread doesn't make the thread effectively executed right now.
It is the way which works multithreading.
From Thread.start() documentation :
Causes this thread to begin execution; the Java Virtual Machine calls
the run method of this thread.
The result is that two threads are running concurrently: the current
thread (which returns from the call to the start method) and the other
thread (which executes its run method).
The main thread is currently executed as you invoke t.start(); .
The thread will at a time be paused by the JVM but you don't master when.
In your specific case, you will get a reproducible behavior.
As after t.start();, you have a statement very fast to execute :
threadMessage("Waiting for MessageLoop thread to finish");
it never doesn't let the main thread to be paused and the new thread to be effectively run.
Add after t.start();, some statements that take more time to be executed in the main thread or invoke sleep() on it and you should see a different behavior.

Join() in multithreading

According to join definition, the join thread executes till its execution is complete and is not prempted in the middle (correct me if i am wrong) .But in the following code: the join thread t1 doesnt stop the main thread to take the control in between the execution of t1. why so ?
public class JavaAtomic {
public static void main(String[] args) throws InterruptedException {
ProcessingThread pt = new ProcessingThread();
Thread t1 = new Thread(pt, "t1");
t1.start();
Thread t2 = new Thread(pt, "t2");
t2.start();
t1.join();
t2.join();
System.out.println("Processing count=" + pt.getCount());
}
}
class ProcessingThread implements Runnable {
private int count;
#Override
public void run() {
for (int i = 1; i < 5; i++) {
processSomething(i);
count++;
System.out.println(Thread.currentThread()+"---"+getCount()) ;
}
}
public int getCount() {
return this.count;
}
private void processSomething(int i) {
// processing some job
try {
Thread.sleep(i * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
output:
Thread[t1,5,main]---1
Thread[t2,5,main]---2
Thread[t1,5,main]---3
Thread[t2,5,main]---4
Thread[t1,5,main]---5
Thread[t2,5,main]---5
Thread[t2,5,main]---6
Thread[t1,5,main]---7
Processing count=7
Many Thanks
Jayendra
Here's what is happening in your example:
Main thread starts running, instantiates and kicks off t1 and t2
t1 runs a little
t2 runs a little
The main thread joins on t1 and blocks until t1 finishes
t1 and t2 keep doing their thing. We continue to see output from them. Main thread is blocking.
t1 finishes and main thread unblocks
Main thread joins on t2. However, it just so happens that in your particular output example, t2 actually finished before t1, which is entirely possible under the randomness of the thread scheduler. So, the main thread doesn't block on this second join() call because t2 is already done.
The main thread runs to completion and program exits.
ADDITION
The above answer is unchanged. However I noticed a thread safety issue in your code. You have multiple threads incrementing the count variable in the shared ProcessThread instance by using the ++ operator. Please note that ++ is not atomic (see this article), because it really consists of four operations: reading the current value of count, adding 1 to it, writing the new value back to count, and returning the value to the caller. In the gaps between those four operations, the thread scheduler could pre-empt the current thread and slip in another one carrying an outdated value read from count. Try increasing the number of threads and decreasing the time in your sleep() call and you will see the current count number appear inconsistent (same number may appear more than once, lower before higher, etc.) count becomes subject to race conditions between threads. The solution is to either enclose all reads/writes to count in synchronized, or to use a java.util.concurrent.atomic.AtomicInteger.
Join stops the thread that calls join. It has no effect on the thread joined.
when you call t1.join(), it won't have any effect on t1's execution. i.e It can't stop t1. t1.join() will wait for t1 to finish and then go forward in the execution.
When main thread reaches the code t1.join() both t1 and t2 have been started and now main thread will wait for t1 to finish. But we can't predict the behaviour of running of t1 and t2, we can only assure that the last line of main function System.out.println("Processing count=" + pt.getCount()); will execute only after thread t1 and t2 finish execution.

Threads to print series in Sync

I am learning Java Threads these days and want to clear few basic doubts.
My aim is to have 3 threads each printing their respective jobs
Thread 1 will print series : 1 4 ...
Thread 2 will print series : 2 5 ...
Thread 3 will print series : 3 6 ...
I have wrote below code, and things are working fine but want to verify is my code correct??
Also, is mapOfPrinter.wait() is same as synchronized (mapOfPrinter)?
I mean to say, calling mapOfPrinter.wait(), makes the current thread (ie one who has acquired monitor) to release the lock and go in waiting state.
Also, if any thread has acquired a lock then another thread who encounters
synchronized (mapOfPrinter) has to wait for lock to be released. In both cases, waiting is same or it differs?
If multiple threads are waiting for lock to be freed (mapOfPrinter here), then doing mapOfPrinter.notify() will awake which thread among waiting threads.
how we can awake only particular thread among the list of threads waiting on same mutex?
Let me know if I am not clear in explaining the question.
public class Main {
public static void main(String[] args) {
Map<String, Printer> mapOfPrinter=new HashMap<String, Printer>();
Printer p1 = new Printer(1, mapOfPrinter);
Printer p2 = new Printer(2, mapOfPrinter);
Printer p3 = new Printer(3, mapOfPrinter);
Thread t1 =new Thread(p1, "1");
Thread t2 =new Thread(p2, "2");
Thread t3 =new Thread(p3, "3");
mapOfPrinter.put("1", p1);
mapOfPrinter.put("2", p2);
mapOfPrinter.put("3", p3);
t1.start();
t2.start();
t3.start();
}
}
class Printer implements Runnable{
int data;
Map<String, Printer> mapOfPrinter;
static volatile int seriesToPrint=1;
public Printer(int data, Map<String, Printer> mapOfPrinter) {
this.data=data;
this.mapOfPrinter=mapOfPrinter;
}
#Override
public void run() {
while(true){
synchronized (mapOfPrinter) {
if(seriesToPrint>mapOfPrinter.size()){
seriesToPrint=1;
}
Thread currThread = Thread.currentThread();
if(!(currThread.getName().equals(String.valueOf(seriesToPrint)))){
mapOfPrinter.notifyAll();
try {
mapOfPrinter.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
Printer p = mapOfPrinter.get(String.valueOf(seriesToPrint));
System.out.println("Thread"+ currThread.getName() + " = " + p.data + " ");
p.data=p.data+3;
seriesToPrint++;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Verifying your code is correct is a wide and difficult subject. You can get startet with testing it, and then do more testing. This will give you a confidence that your code works, but will never tell you if it is really correct. The other way to go is to do a formal verification, but this is difficult and time consuming.
xxx.wait() is totally different from synchronized(xxx) {}. Using synchronized, you make sure only a single thread at a time can enter specific regions of code. xxx.wait() makes the current thread wait until some other thread calls xxx.notify(). As you seem to have missed something fundamental here, I'd suggest digging through http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
notify() will wake up one random thread.
afaik this is not possible. You could however use a different lock for each thread, and use the respective lock.

Basic Java threading and runnable pattern

I have a problem with understanding this code. I have only a couple of hours' knowledge of Java.
Here is the code :
// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
And here is output of it :
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Here are my questions.
I want to understand the pattern the code follows. According to me,
First of all, the Program should start to execute the main() function. So, instance of NewThread should be initialized.
Then, I have to go into NewThread constructor and write Child thread: Thread[Demo Thread,5,main]
After that t.start() comes and therefore Program should execute public void run() (AM I WRONG HERE ?? )
In public void run(), I think I should have gotten an output Child Thread 5, but instead I got Main Thread 5. I wonder why ??
Is there anyone to help me ?? Thanks in advance.
t.start() creates a new thread, and calls run() from that. At that point, there are two threads running independently: the one that called start(), and the new one. The original thread returns from the constructor and then starts executing the loop in the main() method.
As the two threads are independent, there's no guarantee which thread will reach a call to System.out.println first. In the sample output that you've given, it so happens that the original thread gets to print first. It could easily happen the other way round though.
As an aside, if you're new to Java I would suggest you learn the basics of the language before you get to threading. There's nothing in your question which indicates that you're confused, but threading is a relatively advanced topic, and it's worth being comfortable with the general language behaviour before you get that far, IMO. That way you can be confident that any odd behaviour you see really is due to threading and not to misunderstanding other parts of the language.

Using Thread.run() execute two threads simultaneously in an Enhanced loop

public abstract class Multithread implements Runnable{
static Thread t1 = new Thread(){
public synchronized void run(){
try {
for(;;){
System.out.println("java");
t1.sleep(300);
}
} catch (Exception e) {
System.out.println("Exception"+e);
}
}
};
static Thread t2 = new Thread(){
public synchronized void run(){
try{
for(;;){
System.out.println("world");
t2.sleep(300);
}
}catch(Exception e){
System.out.println("Exception"+e);
}
}
};
public static void main(String[] args) {
try{
t1.start();
t2.start();
}catch(Exception e){
System.out.println("Exception "+e);
}
}
#Override
public void run() {
System.out.println("running");
}
}
Excepted O/P:
java
world
java
world
java
world
.
.
.
.
observed
I tried using sleep() for the threads,they are getting overlapped at some point of time like this-
java
java
world
java
world
world
java
..
Expected
i need these two threads to run in parallel and it should not get overlapped,either of the thread can be started. Any idea?
Threads are not accurate in time. If they depend on each other, you have to manually synchronize, like : How to execute two threads Sequentially in a class
You can achieve this by having a counter, if the counter is 0 thread 1 executes, increments the counter and calls notyfyAll() on the counter, if the counter is 1 thread 1 calls wait() on the counter. And vice versa for thread 2.
When you execute two threads in parallel, each one of them is executed independently by the underlying operating system. The task scheduler can decide when to execute which thread. This can result in uneven time distribution like you are experiencing.
One solution for this is to use shared Semaphores to lock each thread until the other one has finished its task. Each thread would then take two semaphores, one for itself and one for the other thread. Both semaphores would start with one permit, so the first release() call doesn't block. The threads would then work like that (psudocode):
for (;;) {
otherThreadSemaphore.acquire(); // blocks until the other thread called release()
performWork();
ownThreadSemaphore.release(); // allows the other thread to perform another iteration
}
Another would be to move the infinite loop out of the threads. In each iteration of the loop you spawn both threads, then use thread.yield() to wait until both threads are finished and then the loop starts again creating two new threads. But note that creating threads can be an expensive operation, so you should only do this when the threads do considerable amount of work in each iteration so that this doesn't matter much.

Categories