多线程实现资源共享

菜鸟之多线程实现资源同步,信息共享,以卖票为例,这里实现的是Runnable接口用synchronized加锁实现同步

public class ThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        myThread td = new myThread();
        myThread td1 = new myThread();
        System.out.print(" ");

        new Thread(td).start();
        new Thread(td1).start();
        Thread.sleep(1000);
        td.flag = false;

    }
}
 class  myThread implements Runnable{
    private static int ticket = 100;

    boolean flag = true;


    @Override
    public void run() {
        synchronized(this){
            sale();
        }

    }
    public void sale() {
        for (int i = 0; i < 1000; i++) {
            if (ticket > 0) {
                System.out.println(Thread.currentThread().getName() + "卖票:ticket = " + ticket--);
            }
        }
    }
}

`自己的学习之路,加油

发布了3 篇原创文章 · 获赞 0 · 访问量 22

猜你喜欢

转载自blog.csdn.net/qq_38829655/article/details/105023791