首页 > 代码库 > java知识点 --多线程

java知识点 --多线程

package Run;


class Ticket implements Runnable{
    private int tickets = 100;
    public int total = 0;
    Object obj = new Object();
    
    public void sell()
    {
        while ( true ) {
            synchronized ( obj ) {
                if ( tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + "..." + tickets--);
                    total++;
                }
                else {
                    break;
                }
            }
        }
    }
    
    @Override
    public void run() {
        sell();
    }
}


class Main {
    public static void main(String[] args) throws InterruptedException {
        Ticket t = new Ticket();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        t1.start();
        t2.start();
        for (int i = 0; i < 9999;++i)
            System.out.print("");
        System.out.println(t.total); //测试卖出的票数
    }
}

 

java知识点 --多线程