多线程练习 卖票程序
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.lang.Thread.sleep;
/**
* @author admin
* @version 1.0.0
* @ClassName Tickets_selling.java
* @Description TODO
* @createTime 2021年11月18日 14:31:00
*/
public class Tickets_selling implements Runnable {
static int tickets = 200 ;
static Object ob = "key";
public Tickets_selling(){};
public Tickets_selling(int tickets) {
this.tickets = tickets ;
}
void sell(){
while (tickets > 0){
synchronized (ob){
if (tickets > 0){
System.out.println(Thread.currentThread().getName() + "卖出了第" + tickets + "张票" );
tickets -- ;
} else {
System.out.println("票卖完了");
}
}
try {
sleep(1000);//休息一秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
sell();
Thread.yield();
}
}
调用程序
public class Test {
// public static void main(String[] args) {
// ExecutorService pool = Executors.newFixedThreadPool(5);
// for (int i = 0; i < 5; i++) {
// pool.execute(new Thread(new Practice()));
// }
// pool.shutdown();
// System.out.println(Arrays.toString(Practice.nums));
// }
public static void main(String[] args) {
int ThreadSize = 5 ;
ExecutorService pool = Executors.newFixedThreadPool(ThreadSize);
for (int i = 0; i < 5; i++) {
pool.execute(new Tickets_selling());
}
pool.shutdown();
}
}
问题 多线程只有一个线程运行到程序结束
可能存在的问题