卖票的代码,无法实现完整的多线程,只有一两个线程会输出。
import java.util.Scanner;
class MyThread implements Runnable{
private int ticket; //票数
private String name; //线程名称
public MyThread() {
super();
}
public MyThread(int ticket,String name) {
super();
this.ticket = ticket;
this.name = name;
}
public int getTicket() {
return ticket;
}
public void setTicket(int ticket) {
this.ticket = ticket;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void run() { //控制线程输出
int t = this.ticket;
synchronized(this){ //同步线程
for(int i = 1;i<=t;i++) {
if(this.ticket>0) {
System.out.println(this.name+",当前余票是:"+(this.ticket-1)+".售出票号是:"+i);
}
this.ticket--;
}
}
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入总的票数:");
int ticketNum = in.nextInt();
System.out.println("请输入窗口数目:");
int num = in.nextInt();
MyThread mt = new MyThread();
for(int i = 1;i<=num;i++) {
mt.setName("售票窗口"+i+"正在售票");
mt.setTicket(ticketNum);
new Thread(mt).start();
}
}
}
以下为代码运行结果:
麻烦大佬们解答一下,谢谢!
ps:为什么在主方法的设置多线程for循环那里,将创建和实例化对象放入for循环中,就无法实现同步线程呢?