2

I am new to MultiThreading , i am writing an application, In that i have two threads T1 and T2. In T1 i have 15 statements to print, and T2 i have 15 statements to print. I like to wait T2 for some time after T1 executed statement 5 and continue T2 after T1 executes statement 10. I have written the code but T2 is not waiting , can any one please explain.

Thread One : T1

public class ThreadOne extends Thread {

public void run() {



    for (int i = 1; i <= 15; i++) {

        System.out.println("This is Thread One " + i);

        if (i == 5) {
            synchronized (Test.threadB) {
                try {
                    Test.threadB.wait();
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        } else if (i == 10) {
            synchronized (Test.threadB) {
                Test.threadB.notify();
            }
        }


    }


}
}  

Thread Two : T2

public class ThreadTwo extends Thread {

public void run() {

    for (int i = 1; i <= 15; i++) {

        System.out.println("This is Thread Two " + i);
    }


}
}  

Test :

public class Test {

static Thread threadA = null;
static Thread threadB = null;

public static void main(String[] args) throws InterruptedException {

    threadA = new ThreadOne();
    threadB = new ThreadTwo();

    threadA.start();
    threadB.start();


}
}

How i expected O/P :
After T1 executed Test.threadB.wait(); when i is 5, no T2 statements has to be printed. after T1 i is 10 , T2 can start printing.

But O/p I am getting is :

This is Thread One 1
This is Thread One 2
This is Thread One 3
This is Thread Two 1
This is Thread Two 2
This is Thread One 4
This is Thread Two 3
This is Thread One 5
This is Thread Two 4
This is Thread Two 5
This is Thread Two 6
This is Thread Two 7
This is Thread Two 8
This is Thread Two 9
This is Thread Two 10
This is Thread Two 11
This is Thread Two 12
This is Thread Two 13
This is Thread Two 14
This is Thread Two 15
This is Thread One 6
This is Thread One 7
This is Thread One 8
This is Thread One 9
This is Thread One 10
This is Thread One 11
This is Thread One 12
This is Thread One 13
This is Thread One 14
This is Thread One 15 

Why Only T2 ststements are executing after T1 i==5 or( This is Thread One 5 is printed) ? Please any one explain.

LMK IND
  • 472
  • 1
  • 5
  • 19
  • 3
    What do you think `Test.threadB.wait();` does and why do you think so? – Sotirios Delimanolis Jun 07 '15 at 19:39
  • i want T2 to wait , so i called wait on T2 object .and after T1 executed i==10 , i am notifying T2 to carry on with work . – LMK IND Jun 07 '15 at 19:42
  • 2
    _i want T2 to wait_ Why do you think `Test.threadB.wait();` achieves that? – Sotirios Delimanolis Jun 07 '15 at 19:42
  • 1
    Not that it solves anything but you should avoid extending Threads. Instead create implementation for `Runnable` and pass it to Thread. Also avoid synchronizing on Thread. – Pshemo Jun 07 '15 at 19:45
  • http://stackoverflow.com/questions/10639763/calling-wait-on-thread-instance-in-java – Sotirios Delimanolis Jun 07 '15 at 19:45
  • http://stackoverflow.com/questions/16197135/java-how-can-the-wait-and-notify-methods-be-called-on-objects-that-are-not – Sotirios Delimanolis Jun 07 '15 at 19:45
  • Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object ---- Java Doc (https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html) , plz correct me if i understood wrong – LMK IND Jun 07 '15 at 19:45
  • http://stackoverflow.com/questions/5121173/java-threads-wait-and-notify-methods – Sotirios Delimanolis Jun 07 '15 at 19:46
  • 2
    _Causes the current thread_ Which is the current thread when you call `Test.threadB.wait();`? – Sotirios Delimanolis Jun 07 '15 at 19:47
  • @SotiriosDelimanolis Test.threadB.wait(), Test.threadB means(static varible referencing to T2) ThreadTwo , so current Thread means T2, so it should wait , please correct me if i am wrong – LMK IND Jun 07 '15 at 19:51
  • 2
    Start making a distinction between a thread and a `Thread` object. `Thread#start()` starts a thread that is identified by a corresponding `Thread` object. Code is executing in that (current) thread and at some point it invokes `Test.threadB.wait()`. What is that current thread? – Sotirios Delimanolis Jun 07 '15 at 19:52
  • 1
    @SotiriosDelimanolis , still not clear could you please explain little bit , I am grateful to you for your help – LMK IND Jun 07 '15 at 19:57
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/79907/discussion-between-user1936201-and-sotirios-delimanolis). – LMK IND Jun 07 '15 at 19:57

2 Answers2

3

I prefer to use classes/interfaces from java.util.concurrent instead of wait/notify as I believe that it makes the code much more readable / less prone to synchronization bugs. In your case you could use a Semaphore that is shared between ThreadOne and ThreadTwo to pause and resume ThreadTwo - initialize the semaphore with one permit, on each iteration ThreadTwo calls availablePermits() and if there is an available permit (return value > 0) then it proceeds, else it calls acquire() causing the thread to block until a permit is available. ThreadOne calls drainPermits() to pause ThreadTwo and then calls release() to allow ThreadTwo to resume.

As noted by Pshemo in the comments, it is good practice to implement Runnable instead of extending Thread - this avoids cluttering up your classes and also lets you pool threads using an ExecutorService.

Runnable runnableOne = // ...
Runnable runnableTwo = // ...
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(runnableOne);
executor.submit(runnableTwo);
Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
  • 1
    This is great and all, but please express it in a way that answers OP's question. – Sotirios Delimanolis Jun 07 '15 at 20:09
  • Agreed with answer, also I'd go with ExecutorService / Callable combination. – kervin Jun 07 '15 at 20:29
  • @SotiriosDelimanolis I read the question as "how do I get this behavior, with no restrictions on implementation," in which case I believe that he'd be better served learning `java.util.concurrent` than `wait/notify`. However, if there are restrictions on implementation (e.g. if this is a homework assignment and the professor specified that `wait/notify` be used) then I'll edit/delete my answer as appropriate. – Zim-Zam O'Pootertoot Jun 07 '15 at 20:43
-3

Just replicate what you have done in ThreadOne to the second one. Threads are meant to make a program's excecution be parallel.

So you don't expect the second thread to wait when you haven't given it any waiting logic.

You should use thread two as the lock in thread one and thread one as the lock in thread two:

Bwire
  • 1,181
  • 1
  • 14
  • 25