aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "synchronization" Watch "synchronization" New topic
Author

synchronization

Vijay pillai
Ranch Hand

Joined: Jan 10, 2001
Posts: 45
hello,
can anyone help me with this pls,
class Vijay
{


public synchronized void viju(int a)
{
int aa=a;
for (int i=0;i<10;i++)
{
System.out.println("ito the method the value is"+aa);
try{
Thread.currentThread().sleep(500);
}catch(Exception e)
{
System.out.println("interrupted");
}
}//end of for.
}

public static void main(String []as)
{
final Vijay v=new Vijay();// an object of type Vijay

Runnable r=new Runnable(){
public void run()
{
v.viju(10);
}
};
Thread t=new Thread(r);
t.start();
final Vijay v1=new Vijay();//another object of type Vijay
Runnable r1=new Runnable(){
public void run()
{
v1.viju(20);
}
};
Thread tt=new Thread(r1);
tt.start();
}
}

*** my question is.
how do i make use of the synchronized method,What i want is only one thread should access the method at one time(even with two different objects)...is this possible.
Pratap Reddy
Ranch Hand

Joined: Jan 05, 2001
Posts: 36
In try{}don't use sleep. Then you will see ten 10 and ten 20's.
Zheng Huang
Ranch Hand

Joined: Dec 20, 2000
Posts: 49
The following code may do what you wanted. The key is to make the method static which means the class (not instance) owns it.
class M2 implements Runnable{
public M2(){
Thread t=new Thread(this);
t.start();}
public void run(){
M1 k=new M1();
k.prin();}
}
class M3 implements Runnable{
public M3(){
Thread t=new Thread(this);
t.start();}
public void run(){
M1 k=new M1();
k.prin();}
}
public class M1{
static synchronized void prin(){
for (int i=0;i<1000;i++)
{System.out.print(i+" "); }
System.out.println("HELLO");
System.out.println("HOW ARE");
System.out.println("YOU ?");
}
public static void main(String ag[]){
M2 m=new M2();
M3 mm=new M3();
}
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: synchronization
 
Similar Threads
Thread target
Runnable object use
synchronized threads
locking an dynamic Object
can we access an instace variable of a thread which is in wait() mode?