您的位置:首页 > 编程语言 > Java开发

针对java实验的思考(四)

2015-12-23 00:42 387 查看

题目:

模拟3个人排队买票,每人买1张票

售票员只有1张五元的钱,电影票五元钱一张

张某拿1张二十元的人民币排在孙某前面买票,孙某拿1张十元的人民币排在赵的前面买票,赵某拿1张五元的人民币排在最后

注意事项:

构造函数前面不能加void!

线程同步中 notifyAll();不需要注明对象。写在synchronized方法的最后就可以。

源代码:

import javax.xml.stream.events.StartDocument;

class test implements Runnable {

Thread a=new Thread(this);

Thread b=new Thread(this);

Thread c=new Thread(this);

int s1=5,s2=10,s3=20;

int s[]={0,0,1};

public synchronized void seller(int sx){

if(sx==5){

System.out.println("张三拿出"+sx+"块钱");

s[2]++;

System.out.println("张三买了票");

}

else if(sx==10){

System.out.println("王大明拿出"+sx+"块钱");

while(s[2]==0) {

System.out.println("王大明要等候");

try {

wait();

} catch (InterruptedException e) {

}

}

s[1]++;

s[2]--;

System.out.println("王大明买了票");

}

else if(sx==20){

System.out.println("赵乐乐拿出"+sx+"块钱");

while(s[1]<1||s[2]<1){

System.out.println("赵乐乐要等候");

try {

wait();

} catch (InterruptedException e) {

}

}

s[0]++;

s[1]--;

s[2]--;

System.out.println("赵乐乐买了票");

}

notifyAll();

}

test(){

a.setName("张三");

b.setName("王大明");

c.setName("赵乐乐");

}

public void run() {

if(Thread.currentThread()==a)

{

seller(s1);

}

if(Thread.currentThread()==b)

{

seller(s2);

}

if(Thread.currentThread()==c)

{

seller(s3);

}

}

}

public class test_thread{

public static void main(String []args){

test t1=new test();

t1.a.start();

t1.b.start();

t1.c.start();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: