【Java】【多线程】卖票

分别继承Thread和实现Runnable,创建三个线程卖票。

package com.itheima;

class MyThread extends Thread{
    private static int tickets = 100;
    @Override
    public void run() {
        while (true){
            if(tickets > 0){
                System.out.println(Thread.currentThread().getName() + ": 卖票,票号为:" + tickets );
                tickets--;
            }else return;
        }
    }
}
public class T {
    public static void main(String[] args) {

        MyThread thread1 = new MyThread();
        thread1.setName("窗口1");
        thread1.start();
        MyThread thread2 = new MyThread();
        thread2.setName("窗口2");
        thread2.start();
        MyThread thread3 = new MyThread();
        thread3.setName("窗口3");
        thread3.start();

    }
}


==========================================================

package com.itheima;

class MyThread implements Runnable{
    private int tickets = 100;
    @Override
    public void run() {
        while (true){
            if(tickets > 0){
                System.out.println(Thread.currentThread().getName() + ": 卖票,票号为:" + tickets );
                tickets--;
            }else return;
        }
    }
}
public class T {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread thread1 = new Thread(myThread);
        thread1.setName("窗口1");
        thread1.start();
        Thread thread2 = new Thread(myThread);
        thread2.setName("窗口2");
        thread2.start();
        Thread thread3 = new Thread(myThread);
        thread3.setName("窗口3");
        thread3.start();

    }
}


【Java】【多线程】卖票

=================================================
【Java】【多线程】卖票
仔细会发现有重票问题。

上一篇:Ubuntu18.04 远程桌面SSH + X转发 + VNC4server(亲测延迟最低远程桌面控制)


下一篇:UltraVNC免安装版,4步教你如何实现在linux下UltraVNC免安装版使用