Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Deciding when to use Threads  RSS feed

 
Poonam Kadu
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Friends,

To understand when I should and when I should'nt be using threads I thought
of the following situation:

class Calculation
{
int i=100,j=10;
public void cal()
{
//Some code which returns a value.
}
}

class Client
{
Calculation c=new Calculation();
public void met1()
{
int z=c.cal();
//some code
}

public staic void main(String args[])
{
Client c=new Client();
c.met1();
}
}
Basically an instance of Client class uses an instance of Calculation class to calculate some values.
In the above case i've only one client object using a Calculation object.
The Calculation object is simply meant to calculate some values,which every client object uses.
But if i've 10 Client object can use Threads ,so that a single Calculation object can be used by these 10 objects.Can I've separate execution threads for each Client object?

If i can use threads ,how should it be done?


cheers
Poonam K.
 
Poonam Kadu
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've done this through

class Calculation
{
int i=10,j=10;
public int cal()
{
return(i+j);
}
}

class Client
{
Calculation ca;
String clientname;

public Client(String s,Calculation ca)
{
this.ca=ca;
clientname=s;
}

public void met1()
{
int j=ca.cal();
System.out.println("\n value= "+j+" "+clientname);
System.out.println("Running Thread = "+Thread.currentThread());
}
};


class MyThread extends Thread
{
Client c;
public MyThread(Client c,String name)
{
super(name);
this.c=c;
}

public void run()
{
c.met1();
}
public static void main(String[] args)
{
Calculation ca=new Calculation();
Client c1=new Client("Client1",ca);
Client c2=new Client("Client2",ca);

MyThread t1=new MyThread(c1,"t1");
MyThread t2=new MyThread(c2,"t2");


t1.start();
t2.start();

try
{
System.out.println("\nMain thread went to sleep");

Thread.sleep(2000);


}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("Hello World!");
}
}

Can the same thing be accomplished by implementing the Runnable Interface
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!