码迷,mamicode.com
首页 > 编程语言 > 详细

多线程之间通信

时间:2014-05-09 08:20:06      阅读:334      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   tar   

bubuko.com,布布扣
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);
        }
    }

}
bubuko.com,布布扣

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

多线程之间通信,布布扣,bubuko.com

多线程之间通信

标签:style   blog   class   code   java   tar   

原文地址:http://www.cnblogs.com/miceal/p/3717649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!