七、多个线程间共享数据的应用



/**
 * 七、多个线程间共享数据的应用
 * 
 * @author dahai 
 * 实例:设计4个线程,其中两个线程每次对j增加1,另外两个线程每次对j减少1,写出程序。
 */
public class MultiThreadShareData {


public static void main(String[] args) {
// TODO Auto-generated method stub
ShareData data = new ShareData();

//方式一、
new Thread(new MyRunnable1(data)).start();
new Thread(new MyRunnable2(data)).start();

//方式二、
new Thread(new Runnable() {


@Override
public void run() {
// TODO Auto-generated method stub

while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
data.decrement();
}
}
}).start();


new Thread(new Runnable() {


@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
data.increment();
}
}
}).start();


}


}






class MyRunnable1 implements Runnable{
private ShareData data;
public MyRunnable1(ShareData data){
this.data = data;
}


@Override
public void run() {
// TODO Auto-generated method stub
data.decrement();
}

}


class MyRunnable2 implements Runnable{
private ShareData data;
public MyRunnable2(ShareData data){
this.data = data;
}


@Override
public void run() {
// TODO Auto-generated method stub
data.increment();
}

}










class ShareData {
private int j = 0;


public synchronized void increment() {
j++;
System.out.println("increment:"+j);
}


public synchronized void decrement() {
j--;
System.out.println("decrement:"+j);
}


}

你可能感兴趣的:(java)