File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronization

 
Vijay pillai
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In try{}don't use sleep. Then you will see ten 10 and ten 20's.
 
Zheng Huang
Ranch Hand
Posts: 49
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic