两个线程交替打印数字和字母

private static Object obj = new Object();
	
	static class T1 implements Runnable {
		@Override
		public void run() {
			synchronized (obj) {
			
				for (int i = 1; i < 27; i++) {
					System.out.print(i + "-");
					
					obj.notify();
					try {
						obj.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				obj.notify();
			}
		}
		
	}
	static class T2 implements Runnable {
		@Override
		public void run() {
			synchronized (obj) {
				for (char ch = 'a'; ch <= 'z'; ch+=1) {
					System.out.print(ch + "-");
					obj.notify();
					try {
						obj.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				obj.notify();
			}
		}
		
	}
	
	private static ReentrantLock lock = new ReentrantLock();
	static Condition c1 = lock.newCondition();
	static Condition c2 = lock.newCondition();
	static class T3 implements Runnable {
		@Override
		public void run() {
			lock.lock();
			for (int i = 1; i < 27; i++) {
				System.out.print(i + "-");
//				c2.signal();
				c1.signal();
				try {
					c1.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			c1.signal();  
			lock.unlock();
		}
		
	}
	static class T4 implements Runnable {
		@Override
		public void run() {
			lock.lock();
			for (char ch = 'a'; ch <= 'z'; ch+=1) {
				System.out.print(ch + "-");
				
				c1.signal();
				try {
//					c2.await();
					c1.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
//			c2.signal();
			c1.signal();
			lock.unlock();
		}
		
	}
	public static void main(String[] args) throws InterruptedException{	
//		new Thread(new T1()).start();
//		new Thread(new T2()).start();
		new Thread(new T3()).start();
		new Thread(new T4()).start();
	}

你可能感兴趣的:(算法)