java实现多线程通信程序

用java实现的多线程通信,实现输入一个人名和性别,立即输出该信息。

package pac;

public class 线程通信 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Q q = new Q();
        new Thread(new producer(q)).start();
        new Thread(new consumer(q)).start();
    }
}

class Q {
    private String name;
    private String sex;
    boolean isFull = false;

    public synchronized void set(String name, String sex)
            throws InterruptedException {
        if (isFull) {
            wait();
        }
        this.name = name;
        try {
            Thread.sleep(10);
        } catch (Exception e) {
            // TODO: handle exception
            e.getMessage();
        }
        this.sex = sex;
        isFull = true;
        notify();
    }

    public synchronized void get() throws InterruptedException {
        if (!isFull) {
            wait();
        }
        System.out.println(this.name + "---->" + this.sex);
        isFull = false;
        notify();
    }
}

class producer implements Runnable {
    Q q = null;

    public producer(Q q) {
        this.q = q;
    }

    public void run() {
        int i = 0;
        while (true) {
            if (i == 0) {
                try {
                    q.set("高延龙", "男");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                try {
                    q.set("哈哈哈", "女");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            i = (i + 1) % 2;
        }
    }
}

class consumer implements Runnable {
    Q q = null;

    public consumer(Q q) {
        this.q = q;
    }

    public void run() {
        while (true) {
            try {
                q.get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

 

posted on 2013-10-08 13:44  tianyuanshgan  阅读(155)  评论(0编辑  收藏  举报

导航