Java线程同步Demo

各个线程依次间隔顺序打印消息

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class TongbuTest {
	private class ThreadDemo implements Runnable{
		private String sign;
		private int delay;
		private int order;
		
		public ThreadDemo(String sign,int delay, int order) {
	        this.sign = sign;
	        this.delay = delay;
	        this.order = order;
        }
		@Override
        public void run() {
	        for(int i=0;i<4;i++){
	        	tongbu2(sign, order);
	        	try {
	                Thread.sleep(delay);
                } catch (InterruptedException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
                }
	        }
        }
		
	}
	
	public TongbuTest(){
		lock = new ReentrantLock();
		condition = lock.newCondition();
		new Thread(new ThreadDemo("A", 2000, 0)).start();
		new Thread(new ThreadDemo("B", 500, 1)).start();
		new Thread(new ThreadDemo("C", 800, 2)).start();
	}
	
	public static final int THREAD_NUMBER = 3;
	public int cnt = 0;
	public Condition condition;
	public ReentrantLock lock;
	
	public void tongbu(String msg, int order){
		lock.lock();
		try {
			while(cnt%THREAD_NUMBER != order){
	            condition.await();
			}
			cnt++;
			System.out.println(msg);
			condition.signalAll();
        } catch (Exception e) {
        	e.printStackTrace();
        } finally{
        	lock.unlock();
        }
	}
	
	public synchronized void tongbu2(String msg, int order){
		try {
			while(cnt%THREAD_NUMBER != order){
	            wait();
			}
			cnt++;
			System.out.println(msg); 
			notifyAll();
        } catch (Exception e) {
        }
	}
	
	public static void main(String [] args) {
	    new TongbuTest();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值