62,614
社区成员
发帖
与我相关
我的任务
分享
public class BT4 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Gun 枪膛=new Gun(5);
枪膛.pop.start();
枪膛.push.start();
}
}
class Gun implements Runnable{
private int cartridge;
private int Max=12;
private int Min=0;
Thread pop,push;
Gun(int cartridge){
this.cartridge=cartridge;
push=new Thread(this);
pop=new Thread(this);
}
public void run(){
if(Thread.currentThread()==push){
while(true){
synchronized(this){
System.out.println("正在压入");
cartridge=cartridge+1;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("已压入");
System.out.println ("还有"+cartridge+"发子弹\n");
}
if(cartridge==Max){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
if(Thread.currentThread()==pop){
while(true){
synchronized(this){
System.out.println("正在 射出");
cartridge=cartridge-1;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("已射出");
System.out.println ("还有"+cartridge+"发子弹\n");
}
if(cartridge==Min){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
public class TestTread {
/**
* @param args
*/
public class Q
{
private String name="陈琼";
private String sex="女";
boolean bFul=false;
public synchronized void put(String name,String sex)
{
if(bFul)
try {
wait();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.name=name;
try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
this.sex=sex;
bFul=true;
notify();
}
public synchronized void get()
{
if(!bFul)
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name+"-->"+sex);
bFul=false;
notify();
}
}
public class Producer implements Runnable
{
Q q=null;
public Producer(Q q)
{
this.q=q;
}
public void run()
{
int i=0;
while(true)
{
if(i==0)
q.put("刘德华", "男");
else
q.put("陈琼", "女");
i=(i+1)%2;
}
}
}
public class Customer implements Runnable
{
Q q=null;
public Customer(Q q)
{
this.q=q;
}
public void run()
{
while(true)
{
q.get();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Q q=new Q();
new Thread(new Producer(q)).start();
new Thread(new Customer(q)).start();
}
}