public class Test_j进程 {
public static void main(String[] args) {
Printer1 p = new Printer1();
//th1线程
Thread th1 = new Thread() {
@Override
public void run() {
try {
p.printA();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//th2线程
Thread th2 = new Thread() {
@Override
public void run() {
try {
p.printB();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//th3线程
Thread th3 = new Thread() {
@Override
public void run() {
try {
p.printC();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//th4线程
Thread th4 = new Thread() {
@Override
public void run() {
try {
p.printD();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//启动线程
th1.start();
th2.start();
th3.start();
th4.start();
}
}
class Printer1{
private static int flag = 1;
//静态成员 标志位 取值1
//1:当前th1执行
//2:当前th2执行
//3:当前th3执行
//4:当前th4执行
int j = 0; //前两个线程对j加1,后两个线程对j减1
//printA
public void printA() throws Exception {
for (int i = 0; i < 10; i++) {
synchronized (this) {
while (flag != 1) {
this.wait(); //锁释放,进入等待
}
j++;
System.out.println("printA加1:" + j);
flag = 2; //修改标志,让th2执行
this.notifyAll(); //唤醒另一个线程
}
}
}
//printB
public void printB() throws Exception {
for (int i = 0; i < 10; i++) {
synchronized (this) {
while (flag != 2) {
this.wait(); //锁释放,进入等待
}
j++;
System.out.println("printB加1:" + j);
flag = 3; //修改标志,让th3执行
this.notifyAll(); //唤醒另一个线程
}
}
}
//printC
public void printC() throws Exception {
for (int i = 0; i < 10; i++) {
synchronized (this) {
while (flag != 3) {
this.wait(); //锁释放,进入等待
}
j--;
System.out.println("printC减1:" + j);
flag = 4; //修改标志,让th4执行
this.notifyAll(); //唤醒另一个线程
}
}
}
//printD
public void printD() throws Exception {
for (int i = 0; i < 10; i++) {
synchronized (this) {
while (flag != 4) {
this.wait(); //锁释放,进入等待
}
j--;
System.out.println("printD减1:" + j);
System.out.println();
flag = 1; //修改标志,让th1执行
this.notifyAll(); //唤醒另一个线程
}
}
}
}