线程BA

作者在 2011-12-27 15:36:36 发布以下内容
import java.awt.*;
import java.awt.event.*;
public class Thread1Frame implements Runnable {
    StringBuffer buffer=new StringBuffer();
    Thread t1,t2;
    Thread1Frame() {
       t1=new  Thread(this);
       t2=new  Thread(this);
    }
    public synchronized void addChar(char c){
        if(Thread.currentThread()==t1){
            while(buffer.length()==0)
                try {
                    wait();
                }
                catch (Exception ex) {
                }
                buffer.append(c);
            
        }    
        if(Thread.currentThread()==t2){
                buffer.append(c);
                notifyAll();
        }    
        
    }
    
    public static void main(String[] s){
        Thread1Frame hello=new Thread1Frame();
        hello.t1.start();
        hello.t2.start();
        while(hello.t1.isAlive()||hello.t2.isAlive()){}
        System.out.println(hello.buffer);
    }
    
    public void run(){
        if(Thread.currentThread()==t1){
            addChar('A');
        }
        
        if(Thread.currentThread()==t2){
            addChar('B');
        }
    }
}
 
java codes | 阅读 858 次
文章评论,共0条
游客请输入验证码
浏览17062次
最新评论