其他分享
首页 > 其他分享> > 使用多线程实现四个窗口共同卖票

使用多线程实现四个窗口共同卖票

作者:互联网

创建票对象
/**
* projectName: testSpring
*
* @author:
* time: 2022/8/20 23:04
* description: 票对象,这里实现Runnable方法来重写Run方法
*/
public class Ticket implements Runnable{
private int ticket=100;//100张票

    @Override
    public void run() {
        while(true) {
            if(ticket<=0) {
                break;
            }
            System.out.println(Thread.currentThread().getName()+" 卖了第"+ticket+"张票");
            ticket--;
        }

    }
}

开始卖票

/**
 * projectName: testSpring
 *
 * @author: 
 * time: 2022/8/20 23:05
 * description:
 */
public class TestTicket {

    public static void main(String[] args) {
        //1创建票对象
        Ticket ticket=new Ticket();
        //2创建线程对象
        Thread w1=new Thread(ticket, "窗⼝1");
        Thread w2=new Thread(ticket, "窗⼝2");
        Thread w3=new Thread(ticket, "窗⼝3");
        Thread w4=new Thread(ticket, "窗⼝4");
        //3启动线程
        w1.start();
        w2.start();
        w3.start();
        w4.start();
    }
}

 

标签:窗口,Thread,卖票,Ticket,start,new,ticket,多线程,public
来源: https://www.cnblogs.com/huangruiwu/p/16609037.html