本帖最后由 谭辉 于 2013-3-20 08:39 编辑
- class Res {
- private String name;
- private String sex;
- 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();
- }
- System.out.println(this.name + "-------------" + this.sex);
- flag = false;
- this.notify();
- }
- }
- class Input implements Runnable {
- private Res r;
- Input(Res r) {
- this.r = r;
- }
- public void run() {
- boolean b = true;
- while (true) {
- if (b) {
- r.set("mike", "man");
- b=false;
- } else {
- r.set("丽丽", "女女女女女");
- b=true;
- }
- }
- }
- }
- class Output implements Runnable {
- private Res r;
- Output(Res r) {
- this.r = r;
- }
- public void run() {
- while (true) {
- r.out();
- }
- }
- }
- 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();
- /*
- Input in = new Input(r);
- Output out = new Output(r);
- Thread t1 = new Thread(in);
- Thread t2 = new Thread(out);
- t1.start();
- t2.start();*/
- }
- }
复制代码 假设set函数拿到了执行权和this锁,进入函数体内时如果flag为true则会进入等待,但这时set函数没有释放锁,则out函数也无法进入,线程不是卡死了吗..为什么还能运行.
|