• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads Synchronization (Urgent)

 
Amit Roy
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Friends
The code below is frm a a person named Billesh Arora who had some questions on a post i failed to understand the 1st question can any 1 pls pls give me a detalied explanation of the code below:
public class Test extends Thread {
public synchronized void run() {
print();
}
public synchronized void print() {
System.out.print("JAVARANCH");
try {
Thread.sleep(5000);
}
catch(InterruptedException ie) {
System.out.println(ie.getMessage());
}
}
public static void main(String arg[]) {
Test t1 = new Test();
Test t2 = new Test();
t1.start();
t2.start();
}
}
The output is javaranch followed by javaranch without any time delay why is the time delay ommited
I am giving the exam on 29th so it is urgent alos whr can i find more of "is a" and 'has a " type of questions
Amit

 
Sahir Shah
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Amit,
The lock is on an object not the class. You are creating two
separate objects here hence one thread does not have to wait for the other one to finish.

Rgds
Sahir
 
asim wagan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<html><body>Hi! I have modified your code to show you how to make an object method a class method and the result you wanted:
<code>
public class Test extends Thread {
public synchronized void run() {
print();
}
public static synchronized void print() {
System.out.print("JAVARANCH ");
try {
Thread.sleep(5000);
}
catch(InterruptedException ie) {
System.out.println(ie.getMessage());
}
}
public static void main(String arg[]) {
Test t1 = new Test();
Test t2 = new Test();
t1.start();
t2.start();
}
}
</code></body></html>
 
faiza haris
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The delay factor is not visible cuz the print() method is run before calling the thread to sleep. However if you change the code as
public class Testsync1 extends Thread {
public synchronized void run() {
print();
}
public synchronized void print() {
System.out.print("JAVARANCH");
try {
Thread.sleep(5000);
System.out.print("JAVARANCH is good");
}
catch(InterruptedException ie) {
System.out.println(ie.getMessage());
}
}
public static void main(String arg[]) {
Testsync1 t1 = new Testsync1();
Testsync1 t2 = new Testsync1();
t1.start();
t2.start();
}
}
then u�d find a possible delay factor........
Hope this helps too
Faiza
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic