本帖最后由 寇龙飞 于 2012-8-24 23:41 编辑
哥们你的代码实在是让我胃疼!!!!
贴上来那么一大段,格式混乱,各种空格(以后用Tab键把),中间还有英文全角格式的括号,原谅我的自我强迫症把,我修改你的代码格式化了五分钟,最后整理好一看,天呐函数调用方法写成这r.set=("","man");,我差点吐血,这不是毕老师视频讲的代码嘛,照着抄过来,是这。。。请原谅我的直接。
我找来我以前学习时的代码贴给你吧(代码是等待唤醒机制那块的):- package com.itheima.bixiangdong;
- /* 黑马程序员_毕向东_Java基础视频教程第12天-03-多线程(线程间通信-等待唤醒机制)
- * 对同一个对象,同时进行向内存入和向外打印
- * */
- class Resource {
-
- private String name;
- private String sex;
- private boolean flag = false;
-
- 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();
- }
-
- synchronized void show() {
- if(!flag)
- try {
- this.wait();
- }
- catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(name +" is "+ sex);
- flag = false;
- this.notify();
- }
- }
- class Input implements Runnable {
-
- private Resource r;
-
- Input(Resource r) {
- this.r = r;
- }
- public void run() {
- int i = 0;
- while(true) {
- if(0 == i)
- r.set("Jack", "man");
- else
- r.set("Rose", "woman");
- i = ++i % 2;
- }
- }
- }
- class Output implements Runnable {
-
- private Resource r;
-
- Output(Resource r) {
- this.r = r;
- }
- public void run() {
- while(true) {
- r.show();
- }
- }
- }
- public class InputOutput {
-
- public static void main(String[] args) {
-
- Resource r = new Resource();
-
- new Thread(new Input(r)).start();
- new Thread(new Output(r)).start();
- }
- }
复制代码 程序是死循环,运行结果为:- Jack is man
- Rose is woman
- Jack is man
- Rose is woman
- Jack is man
- Rose is woman
- Jack is man
- Rose is woman
- Jack is man
- Rose is woman
- Jack is man
- Rose is woman
- Jack is man
- Rose is woman
- Jack is man
- Rose is woman
- Jack is man
- Rose is woman
- Jack is man
- Rose is woman
- Jack is man
- Rose is woman
- Jack is man
- Rose is woman
- .......
复制代码 |