多线程模拟买票,sout输出买票顺序混乱
程序员文章站
2022-06-28 18:23:30
...
多线程模拟买票时通过sout输出出票顺序,发现顺序混乱,想了很久不知道原因,看到其他人说可能是因为sout先输出到缓冲区,最后再输出,我觉得有这种可能,使用list存储出票顺序发现顺序是正确的,因此出票顺序混乱的主要原因应该是sout的输出机制,如果有大佬了解的话,希望可以帮我解惑。提前跪谢大佬!!
package com.fh.controller;
import org.apache.tools.ant.taskdefs.Sleep;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//模拟买票测试线程方法同步
public class DemoLock {
public static void main(String[] args) {
TicketLock ticket = new TicketLock();
new Thread(ticket,"申莹莹").start();
new Thread(ticket,"宋子元").start();
new Thread(ticket,"刘培斌").start();
new Thread(ticket,"黄牛党").start();
}
}
//售票站
class TicketLock implements Runnable{
private Integer ticketNum = 10;
private Boolean flag = true;
private final Lock lock = new ReentrantLock();
private List list = new ArrayList();
@Override
public void run() {
while(flag){
synchronized (ticketNum){
if(ticketNum >= 1){
list.add(ticketNum--);
//输出顺序混乱
System.out.println(ticketNum+1);
}else {
flag = false;
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(list.toString());
}
}
输出结果:
下一篇: 薏仁水对于身体的好处有哪些
推荐阅读