七、初识并发
模拟买票的场景:张三、李四和王五一起买票。
代码:
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--); } } }
结果:发现会买到重复的票,不符合逻辑。后续解决。