1. 程式人生 > >java多執行緒快速入門(九)

java多執行緒快速入門(九)

多執行緒安全問題(賣火車票案例)

package com.cppdy;

class MyThread5 implements Runnable{

    private Integer ticketCount=100;
    @Override
    public void run() {
        while(ticketCount>0) {
            try {
                Thread.sleep(50);
            } catch (Exception e) {
                e.printStackTrace();
            }
            sale();
        }
    }
    
    
public void sale() { System.out.println(Thread.currentThread().getName()+"賣出了第:"+(100-ticketCount+1)+"張票。"); ticketCount--; } } public class ThreadDemo5 { public static void main(String[] args) throws Exception{ MyThread5 mt = new MyThread5(); Thread thread1 = new
Thread(mt,"視窗1"); Thread thread2 = new Thread(mt,"視窗2"); thread1.start(); thread2.start(); } }