多线程问题,三个线程轮流进行,每个线程进行n次操作,共执行n*n*3次操作。本代码用三军攻击做演示,通俗易懂。

package com.yyj.zxy;

public class SanJunFight {
	/**
	 * 三只部队轮流上战场,每只部队在战场上每一轮只能进行n次攻击;
	 * 合计攻击300次则停止攻击;
	 */
	private static int count = 1; //攻击计数器
	private static int part = 1;  //默认第一支部队先进行第一次攻击
	private static int n = 10;    //每次攻击多少次
	
	public static void main(String[] args) {
	  final SanJunFight s = new SanJunFight();
	  
	  //第一支部队攻击线程;
	  new Thread(new Runnable() {
		
		@Override
		public void run() {
			for (int i = 0; i < n; i++) {
				synchronized (s) {
					while(part !=1)
						try {
							s.wait();
						} 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进行下一轮攻击
					s.notifyAll(); //唤醒等待攻击的部队;
				}
			}
		}
	}).start();
	  //第2支部队攻击线程;
	  new Thread(new Runnable() {
		  
		  @Override
		  public void run() {
			  for (int i = 0; i < n; i++) {
				  synchronized (s) {
					  while(part !=2)
						  try {
							  s.wait();
						  } 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; //n次攻击后,由部队3进行下一轮攻击
						  s.notifyAll(); //唤醒等待攻击的部队;
				  }
			  }
		  }
	  }).start();
	  //第3支部队攻击线程;
	  new Thread(new Runnable() {
		  
		  @Override
		  public void run() {
			  for (int i = 0; i < n; i++) {
				  synchronized (s) {
					  while(part !=3)
						  try {
							  s.wait();
						  } 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; //n次攻击后,由部队1进行下一轮攻击
						  s.notifyAll(); //唤醒等待攻击的部队;
				  }
			  }
		  }
	  }).start();
	
	
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值