线程控制

问题:两个线程,线程1输出A,线程2输出B,控制两个线程交替输出5次AB
/** 
 * @author HC 
 * @version 2011
 */  
public class ThreadTest{  
    private synchronized void printA() {//syn:进入该方法便获得该对象锁,其他线程不能进入该对象的其他同步方法
    	for (int i = 0; i < 5; ++i)
        {
    		try {
				System.out.println("A");
    			this.notify(); //唤醒任意在等待t对象的线程进入资源竞争状态(当前就B在等待)
				this.wait(); //释放资源,并进入等待,别的线程notify才能被唤醒
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        }
    }
    private synchronized void printB() {
    	for (int i = 0; i < 5; ++i){
    		try {
    			System.out.println("B");
    			this.notify();
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    	}
    }
    public static void main(String[] args) { 
    	ThreadTest t = new ThreadTest();
    	A thread = t.new A();  
        thread.start();
        try {
			thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        B b = t.new B();  
        b.start();
    }
    
    class A extends Thread{//两个内部类,通过外部类对象new这两个线程产生对此外部类对象进行加锁的机制
    	public void run(){
    		printA();
    	}
    }
    class B extends Thread{
    	public void run(){
    		printB();
    	}
    }
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值