• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

synchronization

 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In try{}don't use sleep. Then you will see ten 10 and ten 20's.
 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
}
}
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic