http://blog.youkuaiyun.com/stellaah/article/details/6864701
我也粘贴一下另外一种写法..嘿嘿~~ 大家多交流多学习
图好玩,写来跑跑,Java基础,挺重要的,代码还是要多写啊
package TraditionalThread;
public class ZhiHuiGuan
{
public static void main(String args[])
{
new ZhiHuiGuan().call();
}
/**
* 轰炸命令启动
*/
private void call()
{
final Army army = new Army();
new Thread(new Runnable()
{
@Override
public void run()
{
for (int i = 1; i <= 60; i++)
{
army.A(i);
}
}
}).start();
for (int i = 1; i <= 60; i++)
{
army.B(i);
}
}
}
class Army
{
/**
* A连轰炸/B连熄火
*/
private boolean isAFire = true;
/**
* A连轰炸任务
*/
public synchronized void A(int taskCount)
{
if (!isAFire)
{
//ShowTime For B连. A连休息
try{this.wait();} catch (InterruptedException e){}
}
for (int i = 1; i <= 12; i++)
{
try{Thread.sleep(50);}catch (Exception e){}
System.out.println("A连正在进行第"+taskCount+"次任务,正在发射第"+(i)+"枚导弹");
}
//A连轰炸完毕,通知B连的兄弟开火
isAFire = false;
this.notify();
}
/**
* B连轰炸任务
*/
public synchronized void B(int taskCount)
{
if (isAFire)
{
//ShowTime For A连. B连休息
try{this.wait();} catch (InterruptedException e){}
}
for (int j = 1; j <= 30; j++)
{
try{Thread.sleep(50);}catch (Exception e){}
System.out.println("B连正在进行第"+taskCount+"次任务,正在发射第"+(j)+"枚导弹");
}
//B连轰炸完毕,通知A连的兄弟开火
isAFire = true;
this.notify();
}
}
其实如果用上并发库里的Lock更爽更简洁...一起进步
package TraditionalThread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ZhiHuiGuanHigh
{
public static void main(String args[])
{
new ZhiHuiGuanHigh().call();
}
/**
* 轰炸命令启动
*/
private void call()
{
final Army army = new Army();
new Thread(new Runnable()
{
@Override
public void run()
{
for (int i = 1; i <= 60; i++)
{
army.A(i);
}
}
}).start();
for (int i = 1; i <= 60; i++)
{
army.B(i);
}
}
}
class ArmyHigh
{
Lock lock = new ReentrantLock();
/**
* A连轰炸/B连熄火
*/
private boolean isAFire = true;
/**
* A连轰炸任务
*/
public void A(int taskCount)
{
if (!isAFire)
{
//ShowTime For B连. A连休息
lock.lock();
}
for (int i = 1; i <= 12; i++)
{
try{Thread.sleep(50);}catch (Exception e){}
System.out.println("A连正在进行第"+taskCount+"次任务,正在发射第"+(i)+"枚导弹");
}
//A连轰炸完毕,通知B连的兄弟开火
isAFire = false;
lock.unlock();
}
/**
* B连轰炸任务
*/
public synchronized void B(int taskCount)
{
if (isAFire)
{
//ShowTime For A连. B连休息
lock.lock();
}
for (int j = 1; j <= 30; j++)
{
try{Thread.sleep(50);}catch (Exception e){}
System.out.println("B连正在进行第"+taskCount+"次任务,正在发射第"+(j)+"枚导弹");
}
//B连轰炸完毕,通知A连的兄弟开火
isAFire = true;
lock.unlock();
}
}