• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread - Confirmation

 
Ranch Hand
Posts: 153
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
lass ThreadA {

static int k;

public static void main(String[] args) {

ThreadB b = new ThreadB();
b.start();

synchronized(b) { // Assume main thread acquires lock before lock ThreadB

try {

b.wait(1);

for (int i = 0; i < 10; i++) { // line (1)

System.out.println("ThreadA : " + k++);
Thread.sleep(1000);
}
} catch (InterruptedException e) {}
}
}
}

class ThreadB extends Thread {

static int k;

public void run() {

synchronized(this) {

try {

for (int i = 0; i < 10; i++) {

System.out.println("ThreadB : " + k++);
Thread.sleep(1000);
}
} catch (InterruptedException ie) {}

notify();
} // line (2)
}
}

/*
Once main Thread comes out of wait state(Coz 1msec has completed)
it waits to acquire lock on Object b before continuing from line (1)
-->which happens only after ThreadB completes line (2)
Am I Right???
So o/p will be ThreadB : 0...ThreadB : 9
followed by ThreadA : 0...ThreadA : 9 */
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are right if the thread run method called before you lock the thread in your main function.

"b.start();" does not directly call run method and thread scheduler will call run method. If your main function lock the thread object first then you will get: "Thread A: 0- 9" first.
 
Girish Nagaraj
Ranch Hand
Posts: 153
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks wise...
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic