有一个题目希望大家帮我改一下
比如车站卖票,有10个窗口,1000张票,就是10个窗口把这1000张票卖掉,怎么能让这10个窗口的票数不重复.我写的代码:
public class A implements Runnable {
private static int count =0;
private int id;
public A(){
super();
count++;
id=count;
}
public void run(){
for(int i=1;i<=1000;i++){
try{
Thread.sleep(60); System.out.println("窗口"+id+"卖出第"+i+"张票");
}catch(Exception e){

e.printStackTrace();
}
}
}
public static void main(String[] args){
Thread thread1;
Thread thread2;
Thread thread3;
Thread thread4;
Thread thread5;
Thread thread6;
Thread thread7;
Thread thread8;
Thread thread9;
Thread thread10;

thread1 =new Thread(new A());
thread2 =new Thread(new A());
thread3 =new Thread(new A());
thread4 =new Thread(new A());
thread5 =new Thread(new A());
thread6 =new Thread(new A());
thread7 =new Thread(new A());
thread8 =new Thread(new A());
thread9 =new Thread(new A());
thread10 =new Thread(new A());

thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();
thread7.start();
thread8.start();
thread9.start();
thread10.start();





}

}
我的这个代码,打印出来的10个窗口的票数全是重复的,要是不重复应该怎么写??

解决方案 »

  1.   

    public class A implements Runnable {
    private static int count = 0;
    private int id;
    private int ci;
    private static int i = 0;
    public A() {
    super();
    count++;
    id = count;
    } public void run() {

    try {
    while(check()) {
    Thread.sleep(60);
    System.out.println("窗口" + id + "卖出第" + ci + "张票");
    }
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    private synchronized boolean check() {

    if(i < 1000) {++i;ci=i;return true;}
    return false;
    } public static void main(String[] args) {
    Thread thread1;
    Thread thread2;
    Thread thread3;
    Thread thread4;
    Thread thread5;
    Thread thread6;
    Thread thread7;
    Thread thread8;
    Thread thread9;
    Thread thread10; thread1 = new Thread(new A());
    thread2 = new Thread(new A());
    thread3 = new Thread(new A());
    thread4 = new Thread(new A());
    thread5 = new Thread(new A());
    thread6 = new Thread(new A());
    thread7 = new Thread(new A());
    thread8 = new Thread(new A());
    thread9 = new Thread(new A());
    thread10 = new Thread(new A()); thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();
    thread5.start();
    thread6.start();
    thread7.start();
    thread8.start();
    thread9.start();
    thread10.start(); }}