我写的好麻烦,不知道谁有简便算法
- public class Demo {
- public static void main(String[] args) {
- Res res = new Res();
- new Thread(new MyThread1(res)).start();
- new Thread(new MyThread2(res)).start();
- }
- }
- class Res {
- private int arr[] = new int[10];
- private int index = 0;
- private boolean flag = true;
- public boolean isFlag() {
- return flag;
- }
- public void setFlag(boolean flag) {
- this.flag = flag;
- }
- public synchronized void add1() {
- if (flag) {
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- arr[index] = (int) (Math.random() * 10);
- System.out.println(Thread.currentThread().getName() + ":" + arr[index]);
- index++;
- setFlag(!flag);
- notify();
- }
- public synchronized void add2() {
- if (!flag) {
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- arr[index] = (int) (Math.random() * 10);
- System.out.println(Thread.currentThread().getName() + ":" + arr[index]);
- index++;
- setFlag(!flag);
- notify();
- }
- }
- class MyThread1 implements Runnable {
- private Res res;
- private int count = 0;
- public MyThread1(Res res) {
- this.res = res;
- }
- @Override
- public void run() {
- while (count < 3) {
- res.add1();
- count++;
- }
- }
- }
- class MyThread2 implements Runnable {
- private Res res;
- private int count = 0;
- public MyThread2(Res res) {
- this.res = res;
- }
- @Override
- public void run() {
- while (count < 3) {
- res.add2();
- count++;
- }
- }
- }
复制代码
|