多线程练习--请用多线程显示,每三个数字为一组,直到30.

时间:2023-02-13 21:08:27

线程A:1
线程A:2
线程A:3
线程B:4
线程B:5
线程B:6

线程A:7
线程A:8
线程A:9
...(直到显示30)

3个一组输出30个数



public class TestSange {
	public static void main(String[] args) {
		  final BlockingQueue queue = new ArrayBlockingQueue(30);
		  final Semaphore sp = new Semaphore(1);
		  final Lock lock = new ReentrantLock();
		  final Condition a = lock.newCondition();
		  final Condition b = lock.newCondition();
		  int  targ=0;
		  for (int i = 1; i <= 30; i++) {
				try {
					queue.put(i);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		  new Thread(new Runnable() {
			@Override
			public void run() {
			     lock.lock();
			     boolean flag=false;
			     while(true){
			    	if(flag){
			    		try {
							a.await();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
			    		flag=false;
			    	}
			    	for(int i=0;i<3;i++){
			    		try {
							System.out.println("线程A"+queue.take());
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
			    	}
			    	b.signal();
			    	flag=true;
			     }
			}
		}).start();
		  
		  new Thread(new Runnable() {
				@Override
				public void run() {
				     lock.lock();
				     boolean flag=false;
				     while(true){
				    	if(flag){
				    		try {
								b.await();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
				    		flag=false;
				    	}
				    	for(int i=0;i<3;i++){
				    		try {
								System.out.println("线程B"+queue.take());
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
				    	}
				    	a.signal();
				    	flag=true;
				     }
				}
			}).start();
		  
		  
		  
	}

}