这是一个关于线程的程序,一个简单的售票线程,售票员有3个5块,a先交20,b交10块,c交5块,所以b必须等待
package com.answer19;import java.applet.*;
import java.awt.*;
import java.awt.event.*;class seller {
int five = 3, ten = 0, twenty = 0; String s = null; public synchronized void rule(int money) {
if (money == 5) {
five = five + 1;
s = "给您入场券,您的钱正好";
answer19_7.text.append("\n"+s);
}
else if(money == 10){
while(five<1){
try{
wait();
}
catch(InterruptedException e){}
}
ten=ten+1;
five=five-1;
s="给您入场券,您给我10块,找您5块";
answer19_7.text.append("\n"+s);
}
else if(money ==20){
while(five<3){
try{
wait();
}
catch(InterruptedException e){}
}
five=five-3;
twenty=twenty+1;
s="给您入场券,您给我20,找您15";
answer19_7.text.append("\n"+s);
}
notifyAll();
}
}
public class answer19_7 extends Applet implements Runnable{
static TextArea text;
seller wang;
Thread a, b, c;
public void init(){
a=new Thread(this); b=new Thread(this); c=new Thread(this);
text=new TextArea();
setLayout(new BorderLayout());
add(text,BorderLayout.CENTER);
wang=new seller();
}
public void start(){
a.start(); b.start(); c.start();
}
public void run() {
if(Thread.currentThread()==a){
wang.rule(20);
}
else if(Thread.currentThread()==b){
wang.rule(10);
}
else if(Thread.currentThread()==c){
wang.rule(5);
}
}
}
我的迷惑是将 while(five<3) 改成 if(five<3) 对程序有什么影响,有什么区别,
感谢您的关注,答对给分
package com.answer19;import java.applet.*;
import java.awt.*;
import java.awt.event.*;class seller {
int five = 3, ten = 0, twenty = 0; String s = null; public synchronized void rule(int money) {
if (money == 5) {
five = five + 1;
s = "给您入场券,您的钱正好";
answer19_7.text.append("\n"+s);
}
else if(money == 10){
while(five<1){
try{
wait();
}
catch(InterruptedException e){}
}
ten=ten+1;
five=five-1;
s="给您入场券,您给我10块,找您5块";
answer19_7.text.append("\n"+s);
}
else if(money ==20){
while(five<3){
try{
wait();
}
catch(InterruptedException e){}
}
five=five-3;
twenty=twenty+1;
s="给您入场券,您给我20,找您15";
answer19_7.text.append("\n"+s);
}
notifyAll();
}
}
public class answer19_7 extends Applet implements Runnable{
static TextArea text;
seller wang;
Thread a, b, c;
public void init(){
a=new Thread(this); b=new Thread(this); c=new Thread(this);
text=new TextArea();
setLayout(new BorderLayout());
add(text,BorderLayout.CENTER);
wang=new seller();
}
public void start(){
a.start(); b.start(); c.start();
}
public void run() {
if(Thread.currentThread()==a){
wang.rule(20);
}
else if(Thread.currentThread()==b){
wang.rule(10);
}
else if(Thread.currentThread()==c){
wang.rule(5);
}
}
}
我的迷惑是将 while(five<3) 改成 if(five<3) 对程序有什么影响,有什么区别,
感谢您的关注,答对给分
而if(five<3){} 只是一个判断 我的认识:它们俩个 不是一个概念 也就是说 循球和判断是两码事!!
站在这个思路上在看看你的程序... <有没有啥想法?????>我这只是一个小小的建议 你可别骂我!!!
**** 北京尚学堂科技java培训 , 为大家服务 , 顺便做点广告 , 请见谅! ****