JAVA 设计代码

2025-12-25 07:35:48
推荐回答(2个)
回答1:

/*
* 主类用与建立3个取款行为线程
*/
public class getMoney
{
public static void main(String args[])
{
card c=new card(100);
new Thread(c,"ID-1").start();
new Thread(c,"ID-2").start();
new Thread(c,"ID-3").start();
System.out.println("3 ID using\t\t\t\t\t\t title 100$");
}
}
/*
* 实现RUNNABLE的银行卡类
*/
class card implements Runnable
{
private static int balance;
public card(int x)
{
this.balance=x;
}
public int view()
{
return balance;
}
public void get(int x)
{
this.balance=this.balance-x;
}
/*
* 同步方法块
*/
public synchronized void run()
{
int num=0;
while(this.view()>0)
{
System.out.println("操作时间:"+num);
this.get(10);
System.out.println(Thread.currentThread().getName()+"get 10$\t\t\t\t\t\t此时余额为"+this.view());

num++;
}
if(this.view()<=0)
{
System.out.println(Thread.currentThread().getName()+"取光了剩下所有的钱");
}
}
}

这个是银行取款的和受票类似,用了同步方法的方式
/*
* 主类用语建立3个售票窗口线程
*/
public class MyRun
{
public static void main(String args[])
{
My t=new My();
new Thread(t,"t1").start();
new Thread(t,"t2").start();
new Thread(t,"t3").start();
System.out.println("开始售票..................");
}
}
/*
*实现RUNNABLE的售票窗口类
*/
class My implements Runnable
{
static int sum=20;
public void run()
{
synchronized("sldf")//同步语句块的方式
{
while(sum>0)
{
System.out.println("票号("+sum+")被卖掉了---------------------------------------售票窗口:"+Thread.currentThread().getName());
sum--;

if(sum<=0)
{
System.out.println("售票窗口:"+Thread.currentThread().getName()+"的票卖完了!");
}
}
}

}
}
用了同步语句块的方式,你要4个窗口在主类多NEW一个线程就可以了

回答2:

这个题目在张孝祥的《JAVA就业培训教程》中有答案