0
点赞
收藏
分享

微信扫一扫

ThreadSync3


package com.shrimpking.t2;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/9/21 21:35
 */
class TestThread3 implements Runnable{

    private int tickets = 20;
    @Override
    public void run()
    {
        while (tickets > 0){
            sale();
        }
    }

    //方法同步
    public synchronized void sale(){
        try
        {
            Thread.sleep(100);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " 出票 " + tickets);
        tickets -= 1;
    }
}

//ch15-18
public class ThreadSync3
{
    public static void main(String[] args)
    {
        TestThread3 test = new TestThread3();

        new Thread(test).start();
        new Thread(test).start();
        new Thread(test).start();
        new Thread(test).start();
    }
}

举报

相关推荐

0 条评论