本帖最后由 宁超 于 2011-10-12 11:45 编辑
- 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 (Exception e) {
- }
- this.name = name;
- this.sex = sex;
- flag = true;
- this.notify();
- }
- }
- public synchronized void Out() {
- if (!flag)
- try {
- this.wait();
- } catch (Exception e) {
- }
- System.out.println(name + "......." + sex);
- flag = false;
- this.notify();
- }
- }
- 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("mike", "man");
- else
- r.Set("小红", "女");
- x = (x + 1) % 2;
- }
- }
- }
- class Output implements Runnable {
- private Res r;
- Output(Res r) {
- this.r = r;
- }
- public void run() {
- while (true) {
- r.Out();
- }
- }
- }
- public class ThreadWaitDemo {
- public static void main(String args[]) {
- Res r = new Res();
- new Thread(new Input(r)).start();
- new Thread(new Output(r)).start();
- }
- }
复制代码 看完比老师后视频写的。但是执行不出来。谁帮看下。 |
|