多线程之间通信

package com.test.thread;

public class TestThread {
    public static void main(String[] args) {
        TestThread testThread = new TestThread();
        Thread thread1 = new Thread(new Thread1(testThread));
        Thread thread2 = new Thread(new Thread2(testThread));
        thread1.start();
        thread2.start();
    }
    public synchronized void show(String threadName,boolean flag,boolean isEnd){
        for(int i=0;i<threadName.length();i++){
            System.out.print(threadName.charAt(i));
        }
        System.out.println();
        if(!flag){//线程1
            this.notify();
            try {
                if(!isEnd){//如果循环完毕则不用等待
                    this.wait();                    
                }
                flag = true;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{//线程2
            this.notify();
            try {
                if(!isEnd){//如果循环完毕则不用等待
                    this.wait();                    
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            flag = false;
        }
    }
}

class Thread1 implements Runnable {
    boolean flag = false;
    TestThread tt = null;
    boolean isEnd = false;
    public Thread1(TestThread tt) {
        this.tt = tt;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            if(i==9){
                isEnd = true;
            }
            tt.show("Thread1", flag,isEnd);
        }
    }
}
class Thread2 implements Runnable {
    boolean flag = true;
    TestThread tt = null;
    boolean isEnd = false;
    public Thread2(TestThread tt) {
        this.tt = tt;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            if(i==9){
                isEnd = true;
            }
            tt.show("Thread2", flag,isEnd);
        }
    }

}

线程1和线程2,线程2执行一次,线程1执行一次。

posted @ 2014-05-08 21:09  942391815  阅读(165)  评论(0编辑  收藏  举报