9.1 设计4个线程对象,两个线程执行减操作,两个线程执行加操作。
package book;
class MyThread implements Runnable {
private int count = 0;
public void run() {
while (true) {
if (Thread.currentThread().getName().startsWith("mul")) {
count--;
} else {
count++;
}
System.out.println(count);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class JiOu {
public static void main(String args[]) {
MyThread mt = new MyThread();
Thread mt1 = new Thread(mt, "mul1");
Thread mt2 = new Thread(mt, "mul2");
Thread mt3 = new Thread(mt, "add3");
Thread mt4 = new Thread(mt, "add4");
mt1.start();
mt2.start();
mt3.start();
mt4.start();
}
}
运行结果:(部分)
-1
-1
-2
0
1
1
0
1
2
3
2
2
1
2
1
2
2
2
3
1
3
2
3
3
1
1
2
3
4