How to run two threads at the same time in java - java

I am new to java and I am trying to learn about threads.
I am expecting an output of alternate hello this is thread one and hello this is thread two. but the output I get is as follows:
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread two
hello this is thread two
hello this is thread two
hello this is thread two
hello this is thread two
Below is my code. Can anyone please help me out to why I am getting this output as opposed to expected. And what is it that I can do to run the two threads in parallel.
public class ThreadDemo {
public static void main(String args[]) {
// This is the first block of code
Thread thread = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread one");
}
}
};
// This is the second block of code
Thread threadTwo = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread two");
}
}
};
// These two statements are in the main method and begin the two
// threads.
// This is the third block of code
thread.start();
// This is the fourth block of code
threadTwo.start();
}
}

Just because threads may interlace does not mean that they will. Your threads simply run too fast. Try adding Thread.sleep() to make them run longer.

The problem here is that PrintStream is synchronized which is not fair.
final Lock lock = new ReentrantLock(true); //create fair lock
//after running this code change it to
//ReentrantLock(false); to see what happens
// This is the first block of code
Thread thread = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
lock.lock();
System.out.println("hello this is thread one");
lock.unlock();
}
}
};
// This is the second block of code
Thread threadTwo = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
lock.lock();
System.out.println("hello this is thread two");
lock.unlock();
}
}
};
// These two statements are in the main method and begin the two
// threads.
// This is the third block of code
thread.start();
// This is the fourth block of code
threadTwo.start();
when a lock is fair it will be alot slower, but when its not fair as in your first case it keeps grabbing the lock over and over before the other thread gets a chance to take it. A fair lock is like a queue. Whoever is queued to take it next gets it.

Depending on the number of CPUs and/or CPU cores, multi-threading may only be simulated by your CPU by giving each thread a certain number of time before another thread is scheduled. See also Wikipedia on "Preemptive Multitasking"
Also, given today's CPUs and many cores and their speed, it may also be that the execution of the first thread already finished before the second one is started.
Also, both threads are battling for the lock in System.out, so they will lock each other out.
Let the threads run for longer times (higher number of iterations), and you will see the interleaving you are expecting.

Your code would work too..add sleep in the first object.
// This is the first block of code
Thread thread = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread one");
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};

If you want to have the threads' bodies wait until both threads are running, you can use something like a CountDownLatch, which can block until its internal counter counts down to zero:
final CountDownLatch latch = new CountDownLatch(2);
Thread thread = new Thread() {
#Override public void run() {
latch.countDown();
latch.await(); // Execution waits here until latch reaches zero.
// Rest of the method.
}
}
Thread threadTwo = new Thread() {
#Override public void run() {
latch.countDown();
latch.await(); // Execution waits here until latch reaches zero.
// Rest of the method.
}
}
thread.start();
threadTwo.start();
(Exception handling omitted for clarity)
This will guarantee that the "interesting bit" of the two threads' run methods will be executing at the same time. However, because of the unfair synchronization on the println() method you are calling, there is no guarantee of how the messages printed by the two threads will be interleaved:
Sometimes they might "perfectly" interleave (1, 2, 1, 2, ...)
Sometimes a few of one might be printed without anything from the other (1, 1, 2, 1, 2, 2, 2, ...)
Sometimes one might print all of its messages before the other (1, 1, 1, 1, 2, 2, 2, 2).

Below code is working...
public class ThreadDemo {
public static void main(String args[]) throws InterruptedException {
// This is the first block of code
Thread thread = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread one");
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
// This is the second block of code
Thread threadTwo = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread two");
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
// These two statements are in the main method and begin the two
// threads.
// This is the third block of code
thread.start();
// This is the fourth block of code
threadTwo.start();
}
}

Your code is working as expected, there is absolutely no guarantee that your implementation will execute in the pre-defined manner you are expecting.
I would suggest that you look at other methods of implementing multithreaded code such as join(), sleep() and finding one that better suits your needs.

Related

Java Multithreading: Make threads execute alternatively

I am completely new to multi threading. Need assistance on the below scenario
Scenario:- I want two threads to execute, such that they have to print the word "PingPong" alternatively. This has to happen three 3 times for both threads.
For example:-
Thread 1 has to print "Ping" and it has to go to wait stage.
Thread 2 has to print "Ping" and it has to go to wait stage as well as notify the other thread.
Thread 1 has to print "Pong" and it has to go to wait stage as well as notify the other thread.
Thread 2 has to print "Pong" and it has to go to wait stage as well as notify the other thread.
The same way both the threads has to print the word 3 times in total.
Coding below:-
package com.test.files;
public class MultiThreadingTest2 implements Runnable {
String lastExecutedThread = "";
Object lockObj = new Object();
private void print(String wordToPrint) throws InterruptedException {
synchronized(lockObj) {
if(lastExecutedThread.equals(Thread.currentThread().getName())) {
System.out.println(Thread.currentThread().getName()+" entered wait stage");
lockObj.wait();
} else {
lastExecutedThread = Thread.currentThread().getName();
System.out.println(Thread.currentThread().getName()+" printed "+wordToPrint);
lockObj.notifyAll();
}
}
}
public MultiThreadingTest2(Object lock) {
this.lockObj = lock;
}
#Override
public void run() {
String[] wordArr = {"Ping", "Pong"};
for(int i = 0; i < 3; i++) {
for(int j = 0; j < wordArr.length; j++) {
try {
print(wordArr[j]);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
Thread t1 = new Thread(new MultiThreadingTest2(lock), "Thread 1");
Thread t2 = new Thread(new MultiThreadingTest2(lock), "Thread 2");
t1.start();
t2.start();
}
}
But I could see the above code has resulted in deadlock. Output as follow:-
Thread 1 printed Ping
Thread 1 entered wait stage
Thread 2 printed Ping
Thread 2 entered wait stage
Thread 1 entered wait stage
I am not sure why this has resulted in deadlock. Reason because, the variable "lastExecutedThread " is created at class level. So it should be stored in heap. If its a local variable, then we can say that it could be in thread stack, so the other thread may not what value it possess and because of which the thread executing the print function will have the "lastExecutedThread" to its name and it will lead to deadlock.
Could you please help on this.
You have to make lastExecutedThread static, otherwise each Thread sees its own instance of it.
Note that if inside the print method lockObj.wait() is called, the wordToPrint passed to this method is never printed. You can slightly adapt your code to avoid this: if your print method returns true if printing was successful, and false otherwise. Then inside your nested for-loop, put your call of print inside a while-loop: while (!print(wordArr[j]));

Can anyone explain this program? We cannot start a thread twice but we are getting an output 1-20.. can anyone explain?

import java.io.IOException;
public class Test implements Runnable {
private int m, n;
public synchronized void run() {
try {
for (int i = 0; i < 10; i++) {
m++;
n++;
Thread.sleep(100);
System.out.println(m + ", " + n);
}
} catch (InterruptedException e) {
}
}
public static void main(String[] args) {
try {
Test a = new Test();
new Thread(a).start();
new Thread(a).start();
} catch (Exception e) {
}
}
}
You are correct that you cannot start the same thread twice. But you aren't doing that here. You are starting two separate threads once each.
Your code is essentially the same as:
Thread t1 = new Thread(a);
t1.start();
Thread t2 = new Thread(a);
t2.start();
You are declaring 2 different threads and running them one after another. If you add the following code.
public synchronized void run() {
System.out.println("thread started");
try {
for (int i = 0; i < 10; i++) {
m++;
n++;
Thread.sleep(100);
System.out.println(m + ", " + n);
}
} catch (InterruptedException e) {
}
System.out.println("thread fininshed");
}
You can easily see where the first thread ends and then the second thread starts.
Each of your threads needs to execute task described in instance of Test class. More precisely in its run method. In your case both threads will need to execute task of Test but they will also need to use same instance of this class (which is stored in a reference).
Problem is that run method is synchronized which means it uses monitor/lock of current instance (this - available via a reference) which means that both threads can't execute it at the same time. To be more precise one of threads will need to wait until other thread will finish execution code from that synchronized block (which is entire body of run).
So in your case
one of your threads will print
enter synchronized block locked on a
print values in range 1-10
exit synchronized block locked on a
so now another thread can
enter synchronized block locked on a
print values in range 11-20 (since m and n will be increased each time in loop)
exit synchronized block locked on a

Thread Synchronization - Synchronizing three threads to print 012012012012..... not working

I am trying to synchronize three threads to print 012012012012.... but it is not working correctly. Each thread is assigned a number which it prints when it receives a signal from main thread. There is something wrong with the following program which I am not able to catch.
public class Application {
public static void main(String[] args) {
int totalThreads = 3;
Thread[] threads = new Thread[totalThreads];
for (int i = 0; i < threads.length; i++) {
threads[i] = new MyThread(i);
threads[i].start();
}
int threadIndex = 0;
while (true) {
synchronized(threads[threadIndex]) {
threads[threadIndex].notify();
}
threadIndex++;
if (threadIndex == totalThreads) {
threadIndex = 0;
}
}
}
}
class MyThread extends Thread {
private int i;
public MyThread(int i) {
this.i = i;
}
#Override
public void run() {
while (true) {
synchronized(this) {
waitForSignal();
System.out.println(i);
}
}
}
private void waitForSignal() {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
You need more coordination. the notify call does not immediately wake up the thread and force it to proceed. Instead, think of notify as sending an email to the thread to let it know that it can proceed. Imagine if you wanted your 3 friends to call you in order. You sent friend 1 an email to call you, waited one second, sent an email to friend 2, waited a second, and sent an email to friend 3. do you think you'd get called in that exact order?
one way to add more coordination would be to have some shared state which indicates whose turn it is. if all your friends could see your house, you could put a number on the outside of the house indicating whose turn it was to call. each friend would wait until they saw their number, and then call.
Here's your problem:
int threadIndex = 0;
while (true) {
synchronized(threads[threadIndex]) {
threads[threadIndex].notify();
}
threadIndex++;
if (threadIndex == totalThreads) {
threadIndex = 0;
}
}
The main thread notifies all threads in the right order. However, your threads are working independently. They may or may not get scheduled at a specific point in time. So the end result may be, that thread 2 is reaching the wait/print lock before thread 1 before thread 0. The final order is not determined by you sending the notifications, but (in essence) by the scheduler.
The solution is to change it this way:
the main thread notifies exactly one thread: thread 0
every thread does his work and when done, notifies the next thread in line
obviously the last thread has to notify thread 0 again.
Another possible solution: In the main thread, you can wait immediately after having notified a thread (in the same synchronized block), like this:
synchronized (threads[threadIndex])
{
threads[threadIndex].notify();
threads[threadIndex].wait(); // try/catch here
}
And in the run method of the thread, you can use notifyAll to wake up the main thread after the thread finished its work:
synchronized (this)
{
waitForSignal();
System.out.println(i);
notifyAll();
}
More sophisticated solutions would involve classes from the java.util.concurrent.locks package.
package threads;
import java.util.concurrent.Semaphore;
public class ZeroEvenOddPrinter {
class Runner extends Thread{
Semaphore prev;
Semaphore next;
int num = 0;
public Runner(Semaphore prev,Semaphore next,int num){
this.prev = prev;
this.next = next;
this.num = num;
}
#Override
public void run(){
while (true) {
try {
Thread.sleep(100);
prev.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (num == 0)
System.out.println(0);
else {
System.out.println(num);
num = num + 2;
}
next.release();
}
}
}
static public void main(String args[]) throws InterruptedException{
Semaphore sem1 = new Semaphore(1);
Semaphore sem2 = new Semaphore(1);
Semaphore sem3 = new Semaphore(1);
ZeroEvenOddPrinter zeo = new ZeroEvenOddPrinter();
Runner t1 = zeo.new Runner(sem1,sem2,0);
Runner t2 = zeo.new Runner(sem2,sem3,1);
Runner t3 = zeo.new Runner(sem3,sem1,2);
sem1.acquire();
sem2.acquire();
sem3.acquire();
t1.start();
t2.start();
t3.start();
sem1.release();
}
}
Here i am using semaphores as triggers for all the three threads. Initially all threads will be blocked on sem1,sem2,sem3. Then i will release the sem1 and first thread will execute then it will release the second thread and so on... The best part is you extend this logic to n number of threads. Good Luck!!!

Scanner(System.in) - how to cancel/skip input waiting

I am just wondering how to control console inputs in separate threads?
I have thread A and thread B and thread C; B and C they both control user input... the thing is I am not pretty sure how to switch between B and C threads the scanIn.nextLine(); because B seems to loop two unnecessary iterations before thread C can interrupt B :(
Main thread:
public class Main
{
private volatile ThreadGroup threadGroup=new ThreadGroup();//contains concurrent hash map...
private volatile TaskManager taskManager=new TaskManager(threadGroup);
private A a=new A(threadGroup);
private B b=new B(threadGroup,taskManager);
private C c=new C(threadGroup);
Main()
{
b.start();
threadGroup.add(a,"A");
threadGroup.add(b,"B");
threadGroup.add(c,"C");
}
public static void main(String args[]){new Main();}
}
TaskManager method snippet:
...
public synchronized void threadCMaybeCanBeStartedLater()
{
this.getThreadGroup().get("A").start();
}
...
thread A code like a (overridden run method invokes):
public void loopIt()
{
Random generator = new Random();
A: while(!this.interrupted())
{
Thread.sleep(1000);
int i=generator.nextInt(100)+1;
int j=generator.nextInt(100)+1;
if(i==j){this.invokeC(); System.out.println("event : i==j");}
}
}
private void invokeC()
{
if(!this.getThreadGroup().get("C").isAlive())this.getThreadGroup().get("C").start();
}
thread B code like a:
public void loopIt() throws InterruptedException
{
Scanner scanIn = new Scanner(System.in);
B: while(!this.isInterrupted())
{
Thread.sleep(1000);
String command= scanIn.nextLine();
...
if(command.equals("a"))
{
System.out.println("a was entered");
this.getTaskManager().threadCMaybeCanBeStartedLater();//
continue;
}
if(command.equals("b"))
{
System.out.println("b was entered");
continue;
}
if(command.equals("c"))
{
System.out.println("c was entered");
continue;
}
else{System.out.println("no such command");}
}
}
thread C (the run method invokes)
public void loopIt() throws InterruptedException
{
getThreadGroup().get("B").interrupt();
Scanner scanIn = new Scanner(System.in);
C: while(!this.isInterrupted())
{
Thread.sleep(1000);
String command= scanIn.nextLine();
...
if(command.equals("d"))
{
System.out.println("d was entered");
continue;
}
if(command.equals("e"))
{
System.out.println("e was entered");
this.interrupt();
break C;
}
if(command.equals("f"))
{
System.out.println("f was entered");
continue;
}
else{System.out.println("no such command");}
}
getThreadGroup().get("B").start();
}
...as you can see, the major code conception (see A thread snippet) is "you don't know when thread C can be started but when it started you need to give it console"; that's all; if it was GUI there was no problem but console-like app makes it quite problematic...
So the question is ... how to interrupt/re-start thread B immediately from thread C in this case?
Thanks
Synchronising Threads Using Thread Class
Thread.interrupt() on its own does not synchronise logic & timing between two threads.
Thread.interrupt() signals that the caller would like the thread to interrupt at a time in the near future. The interrupt() method sets an interrupt flag. The isInterrupted() method checks whether this flag is set (& also clears the flag again). The methods Thread.sleep(), Thread.join(), Object.wait() and a number of I/O methods also check & clear this flag, when throwing InterruptedException.
The thread doesn't immediately pause but continues running code. The internal thread logic is designed & implemented by the developer: continue to run thread code considered atomic/urgent until it gets to an "interruptable point", then check the interrupted flag / catch InterruptedException & then do a clean pause - usually via Thread.sleep(), Thread.join() or Object.wait(), and sometimes by exiting Thread.run() altogether thus stopping the thread permanently.
While all of this is happening the calling thread is still running and will execute an indeterminate amount of code before the interrupt takes effect... hence the lack of synchronisation. There is a lack of guaranteed happens-before condition between the code in one thread and code in the other thread.
Some approaches that do synchronise logic & timing between two threads (creating a happens-before condition):
thread1 calls Thread2.join()
thread1 calls SomeObject.wait() and thread2 calls SomeObject.notify()
Synchronise on a method or block
Quick Review of Your Code:
Thread B runs in an infinite loop - there is no call to interrupt it from any thread and no call for it's thread to wait(). It will, however, temporily block until System.in has more input, and then continue.
Thread A only interrupts itself - cleaner and easier to analyse logic if you don't call this.interrupt() and while(!this.isInterrupted()): just change the while loop into: do { .... } while (i != j)
Thread A only interrupts itself - cleaner and much easier to analyse logic if you don't call this.interrupt() and while(!this.isInterrupted()): just change the while loop into: do { .... } while (!"e".equals(command))
Thread C must make the following calls at the top of it's while loop:
threadB.interrupt();
synchronized(this) {
try {
this.wait();
} catch (InterruptedException ie) {
}
Thread B must make the following call as the last line of code:
synchronized(threadC) {
threadC.notify();
}
Reading from I/O (nextLine()) is a blocking & interruptable operation. Right next to it you introduce Thread.sleep() which is also a blocking & interruptable operation that introduces an artificial delay in your code - it is not necessary; remove.
The only Scanner method you call is nextLine(). You're using it as if it were an InputStreamReader & not doing any scanning. Also, you're not buffering input. If code stays like this, replace 'Scanner scanIn = Scanner(System.in)' with: 'BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))'.
The only ThreadGroup method you call are add() and get(). You're using it as if it were a HashMap & not doing any thread group management. If code stays like this, you may replace 'ThreadGroup' with 'HashMap'. However, even the HashMap seems excessive - could simply pass Threads references to other Threads using constructors/setters and avoid HashMap altogether.
Avoid excessive use of continue inside loops - try to avoid altogether. Best to do this by chaining successive 'if' statements together using '} else if {'...
Potential race condition between main thread and thread B. When thread B is started (from Main()) it may execute many lines of code before the main thread executes any more code - B may call ThreadGroup.get() before main thread has called ThreadGroup.add() x 3. Solution: in Main(), put b.start() after ThreadGroup.add() x 3
In general, "a".equals(command) is better practice than command.equals("a") - it handles nulls, giving correct result without NPE (you seem lucky here - probably won't have nulls).
Suggested Changes:
public class ThreadA extends Thread {
ThreadC threadC;
public void setThreadC(ThreadC threadC) {
this.threadC = threadC;
}
#Override
public void run() {
this.loopIt();
}
public void loopIt() {
Random generator = new Random();
int i, j;
do {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
i=generator.nextInt(100)+1;
j=generator.nextInt(100)+1;
} while (i != j);
threadC.start();
}
}
public class ThreadB extends Thread {
ThreadA threadA;
ThreadC threadC;
public void setThreadA(ThreadA threadA) {
this.threadA = threadA;
}
public void setThreadC(ThreadC threadC) {
this.threadC = threadC;
}
#Override
public void run() {
this.loopIt();
}
public void loopIt() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String command = null;
// loop until interrupted
try {
while (!this.isInterrupted()) {
command = reader.readLine();
if ("a".equals(command)) {
System.out.println("a was entered");
if (threadA.getState() == Thread.State.NEW) {
threadA.start();
}
} else if ("b".equals(command)) {
System.out.println("b was entered");
} else if ("c".equals(command)) {
System.out.println("c was entered");
} else if ("z".equals(command)) {
System.out.println("z was entered");
throw new InterruptedException("Command z interruption");
} else {
System.out.println("no such command");
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (InterruptedException ie) {
}
// Now notify ThreadC - it will wait() until this code is run
synchronized(threadC) {
threadC.notify();
}
}
}
public class ThreadC extends Thread {
ThreadB threadB;
public void setThreadB(ThreadB threadB) {
this.threadB = threadB;
}
#Override
public void run() {
this.loopIt();
}
public void loopIt() {
// Block until the lock can be obtained
// We want thread B to run first, so the lock should be passed into Thread C constructor in an already locked state
threadB.interrupt();
synchronized(this) {
try {
// Put this thread to sleep until threadB calls threadC.notify().
//
// Note: could replace this line with threadB.join() - and remove
// from threadB the call to threadC.notify()
this.wait();
} catch (InterruptedException ie) {
}
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String command = null;
while (!"e".equals(command)) {
try {
command= reader.readLine();
if ("d".equals(command)) {
System.out.println("d was entered");
} else if ("e".equals(command)) {
System.out.println("e was entered");
} else if ("f".equals(command)) {
System.out.println("f was entered");
} else if ("z".equals("command")) {
System.out.println("z was entered");
} else {
System.out.println("no such command");
};
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
}
nextLine() does not respond to interruption. You want to do something like
String command;
if (scanIn.hasNextLine())
command = scanIn.nextLine();
else
Thread.sleep(1000);
You can use flag variables (as global variables) to control the while loop in each thread...
suppose that Thread A has an infinite loop like this
while(true)
while(x == 1){
your code ...
}
Thread.sleep(2000);
}
when Thread b is started you can change x to 0 (suppose x is a global variable) then when Thread b finishes executing change x to 1 at the end of Thread b code...
or you can interrupt the thread from thread itself based of flag value x

How do I make one Java thread return before some of its child threads finish?

I have 2 nested threads.
First thread starts multiple instances of second thread. Each second thread has to sleep for some time (5 seconds).
I want to start the first thread and return a message to user immediately, but it seems my first thread waits until all the children of second thread to finish.
How can I achieve this? Any help?
There are some common mistakes when dealing with java.lang.Thread.
Calling run on the thread instead of start. This is nothing magical about the run method.
Calling static methods on thread instances. Unfortunately this compiles. A common example is Thread.sleep. sleep is a static method and will always sleep the current thread, even if the code appears to be calling it on a different thread.
Rather than dealing with threads directly it is generally better to use a thread pool from java.util.concurrent.
What you should probably do, is create a single thread pool via Executors.newCachedThreadPool(). From your main thread submit Runnables (tasks) to the pool. Return to your main thread a list of Futures.
In Java there exists enough framework code that one rarely should need to deal with threads directly.
It may be helpful to see code. It depends on where you are putting Thread.sleep();.
Like someone else has pointed out with Threads you call start() which is a non-blocking call and actually gets the thread rolling. Calling run() will block until the run() method finishes. See the example code below;
public class Application {
public static void main(String[] args) {
FirstThread firstThread = new FirstThread();
firstThread.start();
System.out.println("Main Method ending");
}
}
public class FirstThread extends Thread {
public void run() {
for(int i = 0; i < 3; i++) {
SecondThread secondThread = new SecondThread(i);
secondThread.start();
}
System.out.println("FirstThread is finishing");
}
}
public class SecondThread extends Thread {
private int i;
public SecondThread(int i) {
this.i = i;
}
public void run() {
while(true) {
System.out.println("Second thread number " + i + " doing stuff here...");
// Do stuff here...
try {
Thread.sleep(5000);
}
catch(InterruptedException ex){
//ignore for sleeping}
}
}
}
}
Which produces the output:
Main Method ending
Second thread number 0 doing stuff here...
Second thread number 1 doing stuff here...
FirstThread is finishing
Second thread number 2 doing stuff here...
Second thread number 0 doing stuff here...
Second thread number 2 doing stuff here...
Second thread number 1 doing stuff here...
I replaced 'run' with 'start' in both first thread and second thread.
It works fine now.
Thanks to all who responded with valueble suggestions.
public class FirstThread extends Thread {
public synchronized void run() {
for(int i = 0; i < 3; i++) {
System.out.println("i="+i);
}
System.out.println("FirstThread is finishing");
}
}
public class SecondThread extends Thread {
public synchronized void run() {
for(int j = 0; j < 3; i++) {
System.out.println("j="+j);
}
System.out.println("Second Thread is finishing");
}
}
public class Application {
public static void main(String[] args) {
FirstThread firstThread = new FirstThread();
SecondThread a=new SecondThread()
firstThread.start();
a.start();
}
}
Output will be:
i=0
i=1
i=2
i=3
FirstThread is finishing
j=0
j=1
j=2
j=3
Second Thread is finishing
You can use the Synchronized keyword which will use to run one thread completely
example
public synchronized void run() //which thread to run completely
{
}

Categories

Resources