| Author |
Question in thread
|
Sagar Shroff
Ranch Hand
Joined: Jun 07, 2011
Posts: 182
|
|
public class Cert extends Thread
{
static int x=10;
public static void main( String args[] ) throws Exception
{
Cert Cert = new Cert();
Thread t1 = new Thread(Cert);
Thread t2 = new Thread(Cert);
t1.start();
t2.start();
}
public synchronized void run()
{
System.out.print(++x + " ");;
}
}
In the above program can the Output be guaranteed ???.........I think the output can be guaranteed as Both the Thread are running on different Objects......Am i Right ??
|
OCJP-90%,OCPWCD-95%
|
 |
Sagar Shroff
Ranch Hand
Joined: Jun 07, 2011
Posts: 182
|
|
sagar shroff wrote:public class Cert extends Thread
{
static int x=10;
public static void main( String args[] ) throws Exception
{
Cert Cert = new Cert();
Thread t1 = new Thread(Cert);
Thread t2 = new Thread(Cert);
t1.start();
t2.start();
}
public synchronized void run()
{
System.out.print(++x + " ");;
}
}
In the above program can the Output be guaranteed ???.........I think the output can be guaranteed as Both the Thread are running on different Objects......Am i Right ??
Or Do the two Threads run on the same Object ...Please Help ??....
|
 |
Rahul Sudip Bose
Ranch Hand
Joined: Jan 21, 2011
Posts: 637
|
|
sagar shroff wrote:
Well, you passed the same runnable Cert to both the threads and the run() method is synchronized.
See if this code helps :
OUTPUT :
|
SCJP 6. Learning more now.
|
 |
Ikpefua Jacob-Obinyan
Ranch Hand
Joined: Aug 31, 2010
Posts: 394
|
|
@Sagar...Please always use code tags when writing programs...it makes it easier to analyse, you will find it at the top of the editor when creating your posts...
If you extend a Thread, override the run() method, pass 'a-Thread' or 'a-Runnable' to the threads constructor and invoke the start() method on the Thread Object, the 'new-thread-of-execution' is guaranteed to start and run to completion, provided there is NO other circumstance that alter the normal flow of the program.
Regards
Ikpefua
|
OCPJP 6.
In Your Pursuit Towards Certification, NEVER Give Up.
|
 |
Sagar Shroff
Ranch Hand
Joined: Jun 07, 2011
Posts: 182
|
|
|
Thanks a lot Rahul......and Jacob yeah I will take care next time...nd thnks.
|
 |
 |
|
|
subject: Question in thread
|
|
|