package test1;
/**
* 设计4个线程,其中2个线程,每次对i加1,另外两个线程,每次对i减一
*
* @author Administrator
*
*/
public class Thread2 {
public static void main(String[] args) {
ShareData d = new ShareData();
for (int i = 0; i < 2; i++) {
new Thread(new Runnable1(d)).start();
new Thread(new Runnable2(d)).start();
}
}
}
/**
* 加
* @author Administrator
*
*/
class Runnable1 implements Runnable {
private ShareData d;
public Runnable1 (ShareData d) {
this.d = d;
}
@Override
public void run() {
d.increment();
}
}
/**
* 减
* @author Administrator
*
*/
class Runnable2 implements Runnable {
private ShareData d;
public Runnable2 (ShareData d) {
this.d = d;
}
@Override
public void run() {
d.decrement();
}
}
class ShareData {
private int i = 0;
public synchronized void increment () {
i++;
System.out.println("加后i为:" + i);
}
public synchronized void decrement () {
i--;
System.out.println("减后i为:" + i);
}
}
标签:ShareData,void,class,线程,new,public From: https://blog.51cto.com/u_21817/6066950