Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Problem

 
Prakash Pillai
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,
I have doubt regarding the Creating of child threads.for example check out the following code.
class newthread implements Runnable
{
Thread t;
String name;
newthread (String tname)
{
name=tname;
t=new Thread(this,name);
System.out.println("New Thread :"+t);
t.start();
}
public void run()
{
try
{
for(int i=5;i> 0;i--)
{
System.out.println(name+":"+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(name+"interrupted");
}
System.out.println(name+"exiting");

}
}

class threadinterface
{
public static void main(String args[])
{
newthread t1 = new newthread("one");
newthread t2 = new newthread("two");
newthread t3 = new newthread("three");
System.out.println("Thread one is alive "+t1.t.isAlive());
System.out.println("Thread two is alive "+t2.t.isAlive());
System.out.println("Thread three is alive "+t3.t.isAlive());
try
{
System.out.println("Waiting for threads to finish");
t1.t.join();
t2.t.join();
t3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
System.out.println("Thread one is alive "+t1.t.isAlive());
System.out.println("Thread two is alive "+t2.t.isAlive());
System.out.println("Thread three is alive "+t3.t.isAlive());

}
}
In the above code i am creating 3 child threads from main thread.Now my q are as follows
1. Can again spwan/create child thread inside child thread.something like Nested try or Nested if ?
2.In inter thread communication i have 3 methods wait(),notify()and notifyall() .Now can wake up a spcific thread from wait state to Runnable state. ?
I need ure valuable advice guys.Thanx in advance.
From,
Prakash
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. Can again spwan/create child thread inside child thread.something like Nested try or Nested if ?

Yes. There is no restriction really where you spawn your new threads. All you need is an instance creation expression (new Thread()) and you can create as many threads as you want.

2.In inter thread communication i have 3 methods wait(),notify()and notifyall() .Now can wake up a spcific thread from wait state to Runnable state. ?

No, there is no way to pick a specific thread that gets notified. You can call notifyAll(), and all threads waiting on an object's lock , or just call notify(), in which case the thread scheduler determines which single thread to wake up.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic