本帖最后由 耿渊博 于 2014-3-25 23:16 编辑
- package com.Thread;
- class Res{
- String name;
- String sex;
- boolean flag;
- }
- class Input implements Runnable{
- Res r = new Res();
- Input(Res r){
- this.r = r;
- }
- public void run(){
- int x = 0;
- while (true) {
- synchronized(r){
- if(r.flag)
- try {
- r.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- //e.printStackTrace();
- }
- if (x == 0) {
- r.name = "Mike";
- r.sex = "man";
- } else {
- r.name = "丽丽";
- r.sex = "女女女女女";
- }
- x = (x + 1) % 2;
- r.flag = true;
- r.notify();
- }
- }
- }
- }
- class Output implements Runnable{
- private Res r;
- Output(Res r){
- this.r = r;
- }
- public void run(){
-
- while(true){
- synchronized(r){
- if(!r.flag)
- try {
- r.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- //e.printStackTrace();
- }
- System.out.println(r.name+"......."+r.sex);
- r.flag = false;
- r.notify();
- }
- }
-
- }
- }
- public class InputOutputDemo {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Res r = new Res();
-
- Input in = new Input(r);
- Output out = new Output(r);
-
- Thread t1 = new Thread(in);
- Thread t2 = new Thread(out);
-
- t1.start();
- t2.start();
-
- }
- }
复制代码
|