本帖最后由 张向辉 于 2013-1-29 11:59 编辑
- <blockquote><font size="3">package com.cxt.Thread;
- import java.util.Scanner;
- /*
- * 在线售票系统,创建多个线程,使他们指向同一个对象,同时启动这些对象,使其一起售票
- * */
- public class Sale_System {
- public static void main(String[] args) {
- Sale_Tickets st1 = new Sale_Tickets();
- // Sale_Tickets st2 = new Sale_Tickets();
- Thread t1 = new Thread(st1);
- Thread t2 = new Thread(st1);
- Thread t3 = new Thread(st1);
- Thread t4 = new Thread(st1);
- Thread t5 = new Thread(st1);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- t5.start();
- }
- }
- /*
- * 实现Runnable接口,有5个线程对象对应5个售票窗口,他们共用100张票
- */
- class Sale_Tickets extends piao implements Runnable {
- public void run() {
- while (super.shengyu > 0) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- synchronized (this) {//使用同步块保证票数不能超出
- if (super.shengyu > 0){
- /*count ++;
- shengyu --;*/
- maipiao();
- System.out.println(Thread.currentThread().getName()
- + "窗口,售出第" + super.count + "张票,"+"还剩"+super.shengyu+"张票");
- }
- }
- /*System.out.println(Thread.currentThread().getName()
- +" "+ count+" "+shengyu);*/
- }
- }
- }
- //卖票类,计算票数
- class piao{
- int count = 0;
- int shengyu = 100;
- public void maipiao(){
- Scanner sc = new Scanner(System.in);
- int i = sc.nextInt();
- count = count + i;
- shengyu = shengyu - i;
- System.out.println(count+" "+shengyu);
- }
- }</font>
复制代码 求大神帮忙啊!我想测试下,线程在调用方法的时候,我通过上面方法知道他被调用了,怎么搞啊
|