本帖最后由 吴刚 于 2013-5-28 23:21 编辑
- <div class="blockcode"><blockquote>class R {
- String name;
- int age;
- boolean f = false;
-
- public synchronized void set(String name, int age) {
- if (f) {
- try {
- this.wait();
- } catch (Exception e) {
- // TODO: handle exception
- }
- this.name = name;
- this.age = age;
- f = true;
- this.notify();
- }
- }
-
- public synchronized void out() {
- if (!f) {
- try {
- this.wait();
- } catch (Exception e) {
- // TODO: handle exception
- }
- System.out.println(name+"..."+age);
- f = false;
- this.notify();
- }
- }
- }
- class Input implements Runnable {
- private R r;
- Input(R r){
- this.r = r;
- }
-
- public void run(){
- int x =0;
- while (true) {
- if(x == 0) {
- r.set("张三",10000);
- }else
- r.set("wad", 1);
- x = (1+x)%2;
- }
- }
- }
- class Output implements Runnable {
- private R r;
- public Output(R r) {
- // TODO Auto-generated constructor stub
- this.r = r;
- }
- public void run() {
- while (true) {
- r.out();
- }
- }
- }
- public class InOutTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- R r = new R();
- new Thread(new Input(r)).start();
- new Thread(new Output(r)).start();
-
- }
- }
复制代码 大家帮忙看看,并且我还有点疑问,就是boolean flag = false;那么使用 if(!flag)和if(flag == true)是一个意思吧,不知道大家常用的是那个....
|