以下是代码:- package thread2;
- class Res {
- private String name;
- private String sex;
- private boolean flag = false;
- public synchronized void set(String name, String sex) {
- if (flag)
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- this.name = name;
- this.sex = sex;
- flag = true;
- this.notify();
- }
- public synchronized void out() {
- if(!flag)
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- flag=false;
- this.notify();
- }
- System.out.println((name + "........." + sex));
- }
- }
复制代码- package thread2;
- public class Input implements Runnable {
- private Res r;// 建立一个引用
- Input(Res r) {
- this.r = r;
- }
- public void run() {
- int x = 0;
- while (true) {
- if (x == 0)
- r.set("milk", "man");
- else
- r.set("丽丽", "女女女女女女女女女");
- x = (x + 1) % 2;
- }
- }
- }
复制代码- package thread2;
- public class Output implements Runnable {
- private Res r;
- Output(Res r) {
- this.r = r;
- }
- public void run() {
- while(true){
- r.out();
- }
- }
- }
复制代码- package thread2;
- public class InputOutputDemo
- {
- public static void main(String[] args)
- {
- Res r=new Res();
- new Thread(new Input(r)).start();
- new Thread(new Output(r)).start();
- }
- }
复制代码 以下是打印结果,打印的全部都是这样的,不应该是交替打印吗?如打印完milk....man后再打印丽丽......女女女女女女?:
milk.........man
milk.........man
milk.........man
milk.........man
milk.........man
milk.........man
|
|