首页  

两个线程,一个输出字母,一个输出数字,交替输出1A2B3C4D5E6F     所属分类 java 浏览量 1067
线程之间的交互协作 使用 通知等待机制

ReentrantLock 
Condition
await
signal

或者使用  Object  wait notify  notifyAll


public class NumAndAlphaPrint2 {

	private static final ReentrantLock lock = new ReentrantLock();
	private static final Condition numPrint = lock.newCondition();
	private static final Condition alphaPrint = lock.newCondition();
	
	private static final long SLEEP_TIME = 500;

	public static void main(String[] args) throws Exception {
		Thread numPrintThread = new NumPrintThread();
		Thread alphaPrintThread = new AlphaPrintThread();
		
        // 字母打印线程先启动
		alphaPrintThread.start();
		
		// 启动数字打印线程
	    numPrintThread.start();
		
		
	}
	
	
	private static void doSleep(long time){
		if(time<=0){
			return;
		}
		try{
			Thread.sleep(time);
		}catch(Throwable e){
			//
		}
	}

	static class NumPrintThread extends Thread {
		public void run() {
			String str = "123456";
			int len = str.length();
			for (int i = 0; i < len; i++) {
				
				System.out.print(str.charAt(i));
				doSleep(SLEEP_TIME);
				
				// 通知 字母打印线程
				lock.lock();
				try {	
					alphaPrint.signal();
	            } catch (Throwable e) {
					System.out.println("alphaPrint.signal error," + e);
				} finally {
					lock.unlock();
				}
				
				lock.lock();
				try {
					numPrint.await();
				} catch (Throwable e) {
					System.out.println("numPrint.await() error," + e);
				} finally {
					lock.unlock();
				}
				
			}
		}
	}

	static class AlphaPrintThread extends Thread {
		public void run() {
			String str = "ABCDEF";
			int len = str.length();
			for (int i = 0; i < len; i++) {
				// 先 await ,等待 通知 
				lock.lock();
				try {
					alphaPrint.await();
				} catch (Throwable e) {
					System.out.println("alphaPrint.await() error," + e);
				} finally {
					lock.unlock();
				}
				System.out.print(str.charAt(i));
				doSleep(SLEEP_TIME);
				
				// 通知 数字打印线程
				lock.lock();
				try {	
					numPrint.signal();
	            } catch (Throwable e) {
					System.out.println("numPrint.signal() error," + e);
				} finally {
					lock.unlock();
				}
				
			}

		}
	}

}


	
完整代码

Condition await signal 版本
https://gitee.com/dyyx/hellocode/blob/master/src/action/NumAndAlphaPrint2.java

Object  wait notify  版本 
https://gitee.com/dyyx/hellocode/blob/master/src/action/NumAndAlphaPrint3.java

上一篇     下一篇
devops简介及工具链

jenkins简介

java8 ConcurrentHashMap 锁机制

java面试题合集

单例模式几种实现方式

Mybatis工作原理简介