採用JDK併發包提供的Lock, Condition等類的相關方法控制多線程.

package com.yyj.zxy;

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

public class SanJunFight1 {
	/**
	 * 三隻部隊輪流上戰場,每隻部隊在戰場上每一輪只能進行10次攻擊;
	 * 合計攻擊300次則停止攻擊;
	 */
	
	private static int count = 1; //攻擊計數器
	private static int part = 1;  //默認第一支部隊先進行第一次攻擊
	private static int n = 10;
	
	private static ReentrantLock lock = new ReentrantLock();
	private static Condition con1 = lock.newCondition();
	private static Condition con2 = lock.newCondition();
	private static  Condition con3 = lock.newCondition();
	public static void main(String[] args) {
	  
	  //第一支部隊攻擊線程;
	  new Thread(new Runnable() {
		
		@Override
		public void run() {
			for (int i = 0; i < n; i++) {
					lock.lock();
					while(part !=1)
						try {
							con1.await();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					for(int j=0;j<n;j++){
						System.out.print("部隊:"+part+"進行第"+ count+"次攻擊!");
						int fightTime = 0;
						
						fightTime = 1000;
						System.out.println("攻擊"+fightTime/1000+" 秒結束    >>>>>   本次攻擊完成" );
						count ++;
					}
					System.out.println();
					part = 2; //n次攻擊後,由部隊2進行下一輪攻擊
					con2.signal(); //喚醒等待攻擊的部隊;
				
			}
		}
	}).start();
	  //第2支部隊攻擊線程;
	  new Thread(new Runnable() {
		  
		  @Override
		  public void run() {
			  for (int i = 0; i < n; i++) {
				  lock.lock();
					  while(part !=2)
						  try {
							  con2.await();
						  } catch (InterruptedException e) {
							  e.printStackTrace();
						  }
						  for(int j=0;j<n;j++){
								System.out.print("部隊:"+part+"進行第"+ count+"次攻擊!");
								int fightTime = 0;
								
								fightTime = 1000;
								System.out.println("攻擊"+fightTime/1000+" 秒結束    >>>>>   本次攻擊完成" );
								count ++;
							}
						  System.out.println();
						  part = 3; //5次攻擊後,由部隊3進行下一輪攻擊
						  con3.signal(); //喚醒等待攻擊的部隊;
				  }
			  }
	  }).start();
	  //第3支部隊攻擊線程;
	  new Thread(new Runnable() {
		  
		  @Override
		  public void run() {
			  for (int i = 0; i < n; i++) {
				  lock.lock();
					  while(part !=3)
						  try {
							  con3.await();
						  } catch (InterruptedException e) {
							  e.printStackTrace();
						  }
						  for(int j=0;j<n;j++){
								System.out.print("部隊:"+part+"進行第"+ count+"次攻擊!");
								int fightTime = 0;
								
								fightTime = 1000;
								System.out.println("攻擊"+fightTime/1000+" 秒結束    >>>>>   本次攻擊完成" );
								count ++;
							}
						  System.out.println();
						  part = 1; //5次攻擊後,由部隊1進行下一輪攻擊
						  con1.signal(); //喚醒等待攻擊的部隊;
				  }
			  }
	  }).start();
	
	
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章