多线程,方便在同一个类中操作属性

package decode;//多线程模拟售票问题

import java.util.concurrent.TimeUnit;

public class Test {
    private static int ticket = 10000;//总共10000张票
    private MyThread myThread = null;
    private MyThread myThread1 = null;
    private MyThread myThread2 = null;
    private final Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Test test = new Test();
        test.tttt();
    }

    private void tttt() {
        myThread = new MyThread();
        myThread.start();
        myThread1 = new MyThread();
        myThread1.start();
        myThread2 = new MyThread();
        myThread2.start();
    }

    class MyThread extends Thread {
        @Override
        public void run() {
            while (ticket > 0) {
                 synchronized (lock) {
                    System.out.println(Thread.currentThread().getName() + "卖票,票号为:" + (ticket--));
                }
            }
        }
    }
}



博客图片