其他分享
首页 > 其他分享> > 七、初识并发

七、初识并发

作者:互联网

模拟买票的场景:张三、李四和王五一起买票。

 

代码:

public class TicketThread implements Runnable{

    private int ticket =3;

    public static void main(String[] args) {
        TicketThread ticketThread = new TicketThread();

        new Thread(ticketThread,"张三").start();
        new Thread(ticketThread,"李四").start();
        new Thread(ticketThread,"王五").start();
    }

    @Override
    public void run() {
        while (true){
            if (ticket<=0){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"买到的票号是"+ticket--);
        }
    }
}

 

结果:发现会买到重复的票,不符合逻辑。后续解决。

 

标签:Thread,start,并发,初识,ticketThread,new,public,TicketThread
来源: https://www.cnblogs.com/epiphany8/p/16268981.html