Problems suspending and resuming a thread - java

I am new to java programming and trying threading for the first time. I have created a thread to print the even numbers, and then a thread to print odd numbers. In the odd number thread there is a suspend() method after the number 11 to be printed. And after that there is another block to print odd numbers from 13 to 21. In main() I joined the 2 threads. In main function first I called thread t1(even number) and then joined it with thread t2(odd number). As there is suspend it will suspend the output after printing 11 it pauses there. But after that when i call t2.resume() that doesn't continue printing 13 to 21. Why it isn't printing the rest? and how can I make it resume?
Here's the code, please take a look:
class Hi extends Thread {
public void run(){
try{
for(int i=0; i<=10; i++){
System.out.println("1st: " + (2*i));
sleep(100);
}
} catch(Exception e){
System.out.println(e);
}
}
}
class Hello extends Thread {
public void run(){
try {
for(int i=0; i<=5; i++){
System.out.println("2nd: " +(2*i+1));
}
suspend();
System.out.println(" Resumes again");
for(int i=6; i<=10; i++){
System.out.println("2nd: " +(2*i+1));
}
} catch(Exception e){
System.out.println(e);
}
}
}
public class thread {
public static void main(String args[]){
Hi t1 = new Hi();
Hello t2 = new Hello();
t1.start();
try {
t1.join();
} catch (Exception e) {
}
t2.start();
t2.resume();
}
}
OUTPUT:
1st: 0
1st: 2
1st: 4
1st: 6
1st: 8
1st: 10
1st: 12
1st: 14
1st: 16
1st: 18
1st: 20
Exception in thread "main" 2nd: 1
java.lang.IllegalThreadStateException
2nd: 3
2nd: 5
2nd: 7
2nd: 9
2nd: 11
at java.base/java.lang.Thread.start(Thread.java:791)
at thread.main(thread.java:57)
After this the program isn't exiting, I have to exit the program manually (ctrl+c) in the terminal.

After this the program isn't exiting, I have to exit the program manually (ctrl+c) in the terminal.
Aside from the fact that you should not be using suspend() and resume(), I believe your problem is a classic race condition. The main thread is calling t2.start() and then t2.resume() but the thread is not suspended yet. The main thread throws an exception and then the t2 thread finishes its printing and calls suspend(). There is no one left to resume it so the thread never finishes and you have to control-c your program.
You should make a couple of change to your example code. First off use wait/notify instead of suspend(). For example, have the Hello thread do:
// t2 thread shouldn't use suspend which is deprecated for good reason
synchronized (this) {
wait();
}
Then in the main thread you need to loop until the thread is in a wait state before notify-ing it. Something like:
while (true) {
if (t2.getState() == State.WAITING) {
synchronized (t2) {
t2.notify();
}
break;
}
Thread.sleep(100);
}
These sorts of thread exercises where one thread is locked stepped with another (aside from a join() at the end) are a bad example of threading IMO.
Couple other comments. You should join() with the Hello thread at the end of your code, never catch Exception if you can help it since it hides exceptions that may be the source of problems (at least print them as #GhostCat recommended), and also always re-interrupt your threads when you catch InterruptedException:
try {
t2.join();
} catch (InterruptedException e) {
// always a good pattern
Thread.currentThread().interrupt();
e.printStackTrace();
}

when i call t2.resume() that doesn't continue printing 13 to 21. Why it isn't printing the rest?
#Gray answered that one. TLDR: Your main thread calls t2.resume() before your t2 thread calls suspend().
I am curious to know what Java version you are using. I'm running JDK11 on macOS, and I can't get your program to throw that java.lang.IllegalThreadStateException, but I'm guessing that in whatever JDK and OS you are using, the exception is thrown when your main thread tries to resume() a thread that isn't suspended.
how can I make it resume?
I would use a Semaphore.
Let the t2 thread wait to acquire() a "permit" from a semaphore, and let the main thread release() a permit to the semaphore at the appropriate time.
I changed your program by replacing the suspend() call with sem.acquire(), and by replacing the resume() call with sem.release(). I also threw a call to Thread.sleep() into the main thread before it releases the semaphore so that you can see the pause. Here's the whole thing:
import java.util.concurrent.Semaphore;
class Hi extends Thread { // This class is exactly the same as yours.
public void run(){
try{
for(int i=0; i<=10; i++){
System.out.println("1st: " + (2*i));
sleep(100);
}
} catch(Exception e){
System.out.println(e);
}
}
}
class Hello extends Thread {
private Semaphore sem; // new member variable
public Hello(Semaphore sem) { // new constructor to set the new member.
this.sem = sem;
}
public void run(){
try {
for(int i=0; i<=5; i++){
System.out.println("2nd: " +(2*i+1));
}
// Wait to "acquire" a permit from the semaphore. This won't
// return until the main thread "releases" a permit _to_ the
// semaphore.
sem.acquire();
System.out.println(" Resumes again");
for(int i=6; i<=10; i++){
System.out.println("2nd: " +(2*i+1));
}
} catch(Exception e){
System.out.println(e);
}
}
}
public class Wonk {
public static void main(String args[]){
// Create a semaphore that initially has 0 "permits."
Semaphore s = new Semaphore(0);
Hi t1 = new Hi();
Hello t2 = new Hello(s);
t1.start();
try {
t1.join();
} catch (Exception e) {
}
t2.start();
waitabit(5000); // Sleep 5 seconds, and then...
s.release(); // ...Release the Hounds!!
}
private static void waitabit(int numMilliseconds) {
try {
Thread.sleep(numMilliseconds);
}
catch (Exception e) {
e.printStackTrace();
}
}
}

Related

Thread creation by extending Thread class

This is a simple example about creating a thread by extending the Thread class.
class Count extends Thread {
Count() {
super("my extending thread");
System.out.println("my new thread is started " + this);
start();
}
#Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
System.out.println("count " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("my thread run is over");
}
}
}
public class Multi2 {
public static void main(String[] args) {
Count c = new Count();
try {
while (c.isAlive()) {
System.out.println("main thread is alive untill child thread is alive");
Thread.sleep(1500);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("main thread is over");
}
}
}
And my output was this.
my new thread is started Thread[my extending thread,5,main]
main thread is alive untill child thread is alive
count 0
count 1
main thread is alive untill child thread is alive
count 2
main thread is alive untill child thread is alive
count 3
count 4
main thread is alive untill child thread is alive
count 5
main thread is alive untill child thread is alive
count 6
count 7
main thread is alive untill child thread is alive
count 8
main thread is alive untill child thread is alive
count 9
my thread run is over
main thread is over
My questions are,
01. How come main thread is alive untill child thread is aliveoutput printed before count 0
count 1
02.How come main thread is alive untill child thread is aliveoutput keep printing withing the output of run() method?
Please help me to figure this out.
Thank you.
Count has this line:
Thread.sleep(1000);
Your main program has this line:
Thread.sleep(1500);
Clearly, you're going to get 2 main prints for every 3 count prints. That's why 0 and 1 are next to each other.
As for why you see the main print before the count prints, you can see this:
Count c = new Count();
try {
while (c.isAlive()) {
System.out.println("main thread is alive untill child thread is alive");
Thread.sleep(1500);
You've fired off your c but until your JVM performs a context switch to actually run that thread, you might not see results. The truth is you may, on some systems, see your counter before that. Often, because it's so close to when it kicks off and hasn't yielded yet, you'll see the main print before the counter.
For your second part, your main thread is... keeps printing because it has a loop that tells it to print until your counter thread is no longer alive. They both use System.out so when you look at your console you see them both there.

Synchronized block in the main method

In the below code about the synchronisation between threads, according to the output generated why is the control being transferred to the execution of the new thread despite the lock being acquired for the same object "dt" in the main method ?
public class DemoThread extends Thread {
public DemoThread() {
}
public void run() {
int i=0;
synchronized(this) {
while(++i<=5) {
sum=i;
try{
sleep(1000);
System.out.println("Woke up from sleep");
if(i>=2) this.notify();
}catch(InterruptedException ie) {
ie.printStackTrace();
System.exit(1);
}
}
}
}
private static int sum;
public static void main(String... args) {
DemoThread dt = new DemoThread();
dt.start();
synchronized(dt) {
try{
System.out.println("main here");
dt.wait();
System.out.println("main here again");
System.out.println("sum = " + sum);
}catch(InterruptedException ie){
ie.printStackTrace();
System.exit(1);
}
}
}
}
Output :
main here
Woke up from sleep
Woke up from sleep
Woke up from sleep
Woke up from sleep
Woke up from sleep
main here again
sum = 5
EDIT: I think I was able to find one of the possible flow of the code to explain the output:
1.Main thread enters in the Sync block in the main method.
2.call to the wait is made. Lock released on the dt object
3.New thread enters the while loop as it has the lock on the object dt
4.Thread.Sleep is executed and it doesn't release the lock
5.notify call is made but doesnot wakr the main thread(?)
6.New and the main thread finish the execution
Please correct me if I am wrong
You are close :
1.Main thread enters in the Sync block in the main method.
2.call to the wait is made. Lock released on the dt object
3.New thread enters the while loop as it has the lock on the object dt
4.Thread.Sleep is executed and it doesn't release the lock
5.notify call is made but doesnot wake the main thread(?)
6.New and the main thread finish the execution
Until the step 4, it is correct.
Here is what it happens at the step 5 :
notify() is invoked and the main() thread is so notified.
But it will not have a chance to run again right now.
Why ? Because the DemoThread thread doesn't release the lock.
The notify() method is indeed executed in a loop inside a synchronized statement.
synchronized (this) {
while (++i <= 5) {
sum = i;
try {
sleep(1000);
System.out.println("Woke up from sleep");
if (i >= 2) {
notify();
}
} catch (InterruptedException ie) {
ie.printStackTrace();
System.exit(1);
}
}
And according to Object.notify() javadoc :
The awakened thread will not be able to proceed until the current
thread relinquishes the lock on this object. The awakened thread will
compete in the usual manner with any other threads that might be
actively competing to synchronize on this object; for example, the
awakened thread enjoys no reliable privilege or disadvantage in being
the next thread to lock this object.
So the main() thread could run only as the run() method DemoThread is terminated.
To let the main() thread to run again, you could reverse in the DemonThread run() method, the synchronized statement and the while statement.
You should also make this thread sleep a little bit to let the main() thread to run again.
public void run() {
int i = 0;
while (++i <= 5) {
// let a chance for other threads
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this) {
sum = i;
try {
sleep(1000);
System.out.println("Woke up from sleep");
if (i >= 2) {
notify();
}
} catch (InterruptedException ie) {
ie.printStackTrace();
System.exit(1);
}
}
}
}
Now as i >= 2, as previously, other threads are notified but as the thread leaves the lock as it loops on the while and then sleep 100 ms, the main() thread can run again.
Here is the output :
main here
Woke up from sleep
Woke up from sleep
main here again
sum = 2
Woke up from sleep
Woke up from sleep
Woke up from sleep
The synchronized keyword isn't used to control the execution of a thread, it's used to ensure that only one thread can enter a block of code at any one time.
Typically whole methods can be synchronized or code between {}.
You can also synchronize an object that will be shared between two or more threads, typically some data structure that will be updated by the threads and you need to ensure that the state is consistent and not partially updated.
In your example there is no contention on the synchronize, if you extedt the sample to introduce some object and multiple threads trying to write and read from this object you will get a better understanding.

Java code - Threads blocking each other

I am new to multithreading. I am trying to write a program where I have two threads. One thread prints odd number and then gives up the monitor lock using wait() and similarly other thread prints the even number and gives up the lock after printing the number
I have got 4 classes
Odd.java (print odd numbers between 1-100)
Even.java(print even number between 1-100)
SomeMaths.java( has got logic for printing odd and even numbers )
OEApp.java (Main class that starts the threads)
Problem - My code works as expected most of the times i.e it print number 1 to 100 in order. Both the thread take turns. But I noticed that there is a bug.Sometimes the even thread gets scheduled first and gets below output
2 **********
1 ###############################
After that nothing gets printed, Looks like there is a deadlock situation. I am not able to figure out why. Please help me to understand this
public class SomeMaths {
public synchronized void printOdd(){
for( int i=1;i<=100;i++){
if(i%2 !=0) {
System.out.println(i + " ###############################");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notify();
}
}
public synchronized void printEven(){
for(int i=1;i<=100;i++){
if(i%2 ==0){
System.out.println(i +" **********");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notify();
}
}
}
public class Odd implements Runnable {
SomeMaths sm;
public Odd(SomeMaths sm){
this.sm = sm;
}
#Override
public void run(){
sm.printOdd();
}
}
public class Even extends Thread {
SomeMaths sm;
public Even(SomeMaths sm){
this.sm = sm;
}
#Override
public void run(){
sm.printEven();
}
}
public class OEApp {
public static void main(String[] args) {
SomeMaths sm = new SomeMaths();
Thread odd = new Thread(new Odd(sm));
Thread even = new Thread(new Even(sm));
odd.start();
even.start();
try {
odd.join();
even.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I believe it works this way:
Even thread starts, 1 is odd so it calls notify (notifying no one), then 2 is even so it prints a message and waits
Odd thread starts, 1 is odd so it prints a message and waits
There's no one to call notify so both threads wait forever
What is your purpose for using the synchronize keyword ?
It can only assure you that your function will not be running multiple times at the same time.
I assume that you want one thread to notify another ? Is that right ?
But what if the notify is called before the wait occurred ?
You know that you can use the debugger to see each thread, and thus know where each thread is stuck ?
Please keep in mind, once start is called, you can't know which thread will have cpu time.
Furthermore you are trying to synchronize two threads (by the use of the notify/wait mecanism), but there are other mecanisms that will be proved simpler (e.g. semaphore: each thread having it own semaphore, acquiring it own semaphore and releasing the other one semaphore; initialize each semaphore to 1 and it will go smoothly).
P.S. :
I am forced to post an answer, but it should be a comment; sorry
Why use both runnable and thread interface ? Furthermore your Even class is already a thread, so no use to wrap it once again.
See https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem

Java Threading - Simple wait() notify() issues [duplicate]

I have 2 matrices and I need to multiply them and then print the results of each cell. As soon as one cell is ready I need to print it, but for example I need to print the [0][0] cell before cell [2][0] even if the result of [2][0] is ready first. So I need to print it by order.
So my idea is to make the printer thread wait until the multiplyThread notifies it that the correct cell is ready to be printed and then the printerThread will print the cell and go back to waiting and so on..
So I have this thread that does the multiplication:
public void run()
{
int countNumOfActions = 0; // How many multiplications have we done
int maxActions = randomize(); // Maximum number of actions allowed
for (int i = 0; i < size; i++)
{
result[rowNum][colNum] = result[rowNum][colNum] + row[i] * col[i];
countNumOfActions++;
// Reached the number of allowed actions
if (countNumOfActions >= maxActions)
{
countNumOfActions = 0;
maxActions = randomize();
yield();
}
}
isFinished[rowNum][colNum] = true;
notify();
}
Thread that prints the result of each cell:
public void run()
{
int j = 0; // Columns counter
int i = 0; // Rows counter
System.out.println("The result matrix of the multiplication is:");
while (i < creator.getmThreads().length)
{
synchronized (this)
{
try
{
this.wait();
}
catch (InterruptedException e1)
{
}
}
if (creator.getmThreads()[i][j].getIsFinished()[i][j] == true)
{
if (j < creator.getmThreads()[i].length)
{
System.out.print(creator.getResult()[i][j] + " ");
j++;
}
else
{
System.out.println();
j = 0;
i++;
System.out.print(creator.getResult()[i][j] + " ");
}
}
}
Now it throws me these exceptions:
Exception in thread "Thread-9" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-6" Exception in thread "Thread-4" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-5" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-8" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-7" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-11" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-10" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-12" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
line 49 in multiplyThread is the "notify()"..I think I need to use the synchronized differently but I am not sure how.
If anyone can help this code to work I will really appreciate it.
To be able to call notify() you need to synchronize on the same object.
synchronized (someObject) {
someObject.wait();
}
/* different thread / object */
synchronized (someObject) {
someObject.notify();
}
While using the wait and notify or notifyAll methods in Java the following things must be remembered:
Use notifyAll instead of notify if you expect that more than one thread will be waiting for a lock.
The wait and notify methods must be called in a synchronized context. See the link for a more detailed explanation.
Always call the wait() method in a loop because if multiple threads are waiting for a lock and one of them got the lock and reset the condition, then the other threads need to check the condition after they wake up to see whether they need to wait again or can start processing.
Use the same object for calling wait() and notify() method; every object has its own lock so calling wait() on object A and notify() on object B will not make any sense.
Do you need to thread this at all ? I'm wondering how big your matrices are, and whether there's any benefit in having one thread print whilst the other does the multiplication.
Perhaps it would be worth measuring this time before doing the relatively complex threading work ?
If you do need to thread it, I would create 'n' threads to perform the multiplication of the cells (perhaps 'n' is the number of cores available to you), and then use the ExecutorService and Future mechanism to dispatch multiple multiplications simultaneously.
That way you can optimise the work based on the number of cores, and you're using the higher level Java threading tools (which should make life easier). Write the results back into a receiving matrix, and then simply print this once all your Future tasks have completed.
Let's say you have 'black box' application with some class named BlackBoxClass that has method doSomething();.
Further, you have observer or listener named onResponse(String resp) that will be called by BlackBoxClass after unknown time.
The flow is simple:
private String mResponse = null;
...
BlackBoxClass bbc = new BlackBoxClass();
bbc.doSomething();
...
#override
public void onResponse(String resp){
mResponse = resp;
}
Lets say we don't know what is going on with BlackBoxClass and when we should get answer but you don't want to continue your code till you get answer or in other word get onResponse call. Here enters 'Synchronize helper':
public class SyncronizeObj {
public void doWait(long l){
synchronized(this){
try {
this.wait(l);
} catch(InterruptedException e) {
}
}
}
public void doNotify() {
synchronized(this) {
this.notify();
}
}
public void doWait() {
synchronized(this){
try {
this.wait();
} catch(InterruptedException e) {
}
}
}
}
Now we can implement what we want:
public class Demo {
private String mResponse = null;
...
SyncronizeObj sync = new SyncronizeObj();
public void impl(){
BlackBoxClass bbc = new BlackBoxClass();
bbc.doSomething();
if(mResponse == null){
sync.doWait();
}
/** at this momoent you sure that you got response from BlackBoxClass because
onResponse method released your 'wait'. In other cases if you don't want wait too
long (for example wait data from socket) you can use doWait(time)
*/
...
}
#override
public void onResponse(String resp){
mResponse = resp;
sync.doNotify();
}
}
You can only call notify on objects where you own their monitor. So you need something like
synchronized(threadObject)
{
threadObject.notify();
}
notify() needs to be synchronized as well
I'll right simple example show you the right way to use wait and notify in Java.
So I'll create two class named ThreadA & ThreadB. ThreadA will call ThreadB.
public class ThreadA {
public static void main(String[] args){
ThreadB b = new ThreadB();//<----Create Instance for seconde class
b.start();//<--------------------Launch thread
synchronized(b){
try{
System.out.println("Waiting for b to complete...");
b.wait();//<-------------WAIT until the finish thread for class B finish
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Total is: " + b.total);
}
}
}
and for Class ThreadB:
class ThreadB extends Thread{
int total;
#Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
total += i;
}
notify();//<----------------Notify the class wich wait until my finish
//and tell that I'm finish
}
}
}
Simple use if you want How to execute threads alternatively :-
public class MyThread {
public static void main(String[] args) {
final Object lock = new Object();
new Thread(() -> {
try {
synchronized (lock) {
for (int i = 0; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ":" + "A");
lock.notify();
lock.wait();
}
}
} catch (Exception e) {}
}, "T1").start();
new Thread(() -> {
try {
synchronized (lock) {
for (int i = 0; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ":" + "B");
lock.notify();
lock.wait();
}
}
} catch (Exception e) {}
}, "T2").start();
}
}
response :-
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
we can call notify to resume the execution of waiting objects as
public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
}
resume this by invoking notify on another object of same class
public synchronized notifyJoy() {
joy = true;
notifyAll();
}
For this particular problem, why not store up your various results in variables and then when the last of your thread is processed you can print in whatever format you want. This is especially useful if you are gonna be using your work history in other projects.
This looks like a situation for producer-consumer pattern. If you’re using java 5 or up, you may consider using blocking queue(java.util.concurrent.BlockingQueue) and leave the thread coordination work to the underlying framework/api implementation.
See the example from
java 5:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html
or java 7 (same example):
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html
You have properly guarded your code block when you call wait() method by using synchronized(this).
But you have not taken same precaution when you call notify() method without using guarded block : synchronized(this) or synchronized(someObject)
If you refer to oracle documentation page on Object class, which contains wait() ,notify(), notifyAll() methods, you can see below precaution in all these three methods
This method should only be called by a thread that is the owner of this object's monitor
Many things have been changed in last 7 years and let's have look into other alternatives to synchronized in below SE questions:
Why use a ReentrantLock if one can use synchronized(this)?
Synchronization vs Lock
Avoid synchronized(this) in Java?

How to slow a thread down in JAVA

I have this class in which I run a for loop 10 times. This class implements Runnable interface. Now in main() I create 2 threads. Now both will run loop till 10. But I want to check loop count for each thread. If t1 is past 7 then make it sleep 1 second so as to let t2 complete. But how to achieve this? Please see the code. I attempted but looks totally foolish. Just how to check the data of a thread ???
class SimpleJob implements Runnable {
int i;
public void run(){
for(i=0; i<10; i++){
System.out.println(Thread.currentThread().getName()+" Running ");
}
}
public int getCount(){
return i;
}
}
public class Threadings {
public static void main(String [] args){
SimpleJob sj = new SimpleJob();
Thread t1 = new Thread(sj);
Thread t2 = new Thread(sj);
t1.setName("T1");
t2.setName("T2");
t1.start();
try{
if(sj.getCount() > 8){ // I know this looks totally ridiculous, but then how to check variable i being incremented by each thread??
System.out.println("Here");
Thread.sleep(2000);
}
}catch(Exception e){
System.out.println(e);
}
t2.start();
}
}
Please help
You should use some synchronization object, and not rely on slowing down of threads. I strongly suggest you take a look at one of the classes at java.util.concurrent package. You can use for this CountdownLatch - thread 1 will await on it, and thread 2 will perform the countdown and release the lock, and let thread 1 continue (the release should be done at the end of thread 2 code).
I added a synchronized Block, which can be entered by one thread at a time. Both threads call and enter the method parallel. One thread will win the race and take the lock. After the first thread leaves the block it waits 2 seconds. In this time the second thread can iterate over the loop. I think this behaviour is wanted. If the second thread must not wait 2 seconds, too, you can set some boolean flag, that the first thread finished the block and use this flag in an if statement, which prevents the wait time of the second thread.
class SimpleJob implements Runnable {
int i;
public void run(){
synchronized (this) {
for(i=0; i<8; i++){
System.out.println(Thread.currentThread().getName()+" Running ");
}
}
try {
System.out.println("Here");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(i=0; i<2; i++){
System.out.println(Thread.currentThread().getName()+" Running ");
}
}
public int getCount(){
return i;
}
}
public class Threadings {
public static void main(String [] args){
SimpleJob sj = new SimpleJob();
Thread t1 = new Thread(sj);
Thread t2 = new Thread(sj);
t1.setName("T1");
t2.setName("T2");
t1.start();
t2.start();
}
}
If the goal is to run 2 Runnables in parallel (as Threads) and wait for them both to finish, you can, in increasing order of complexity/power:
Use Thread.join (as suggested by #Suraj Chandran but his reply seems to have been deleted)
Use a CountDownLatch (as also suggested by #zaske)
Use ExecutorService.invokeAll()
EDIT ADDED
First, I don't understand what the magic "if you are at 7 then wait for the other" logic is all about. But, to use Thread.join() from your main code, the code would look like
t1.start(); // Thread 1 starts running...
t2.start(); // Thread 2 starts running...
t1.join(); // wait for Thread 1 to finish
t2.join(); // wait for Thread 2 to finish
// from this point on Thread 1 and Thread 2 are completed...

Categories