Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question in thread

 
Sagar Shroff
Ranch Hand
Posts: 209
Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ??
 
Sagar Shroff
Ranch Hand
Posts: 209
Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 :
 
Ikpefua Jacob-Obinyan
Ranch Hand
Posts: 394
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@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
 
Sagar Shroff
Ranch Hand
Posts: 209
Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Rahul......and Jacob yeah I will take care next time...nd thnks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic