public class MultiThreadShareData {
public static void main(String [] args){
final ShareData1 shareData1 = new ShareData1();
for(int i=0;i<2;i++)
new Thread(new myRunnable1(shareData1)).start();
for(int i=0;i<2;i++)
new Thread(new myRunnable2(shareData1)).start();
}
}
class myRunnable1 implements Runnable{
ShareData1 shareData1;
public myRunnable1(ShareData1 shareData1){
this.shareData1 = shareData1;
}
@Override
public void run() {
while(true){synchronized(shareData1){
System.out.print(Thread.currentThread().getName()+"....");
shareData1.increase();
}
}
};
}
class myRunnable2 implements Runnable{
ShareData1 shareData1;
public myRunnable2(ShareData1 shareData1){
this.shareData1 = shareData1;
}
public void run() {
while(true){synchronized(shareData1){
System.out.print(Thread.currentThread().getName()+"....");
shareData1.decrease();
}
}
};
}
class ShareData1{
private int j=0;
public synchronized void increase(){
j++;
System.out.println("increased After: "+j);
}
public synchronized void decrease(){
j--;
System.out.println("decreased After: "+j);
}
} |