JAVA锁:之多线程简答模拟售货员买票

     测试:

import org.omg.Messaging.SyncScopeHelper;

public class TestThread {
    public static void main(String[] args) {
        Tree tree = new Tree();
        tree.value = 100;
        ThreadPiao t1 = new ThreadPiao("线程1",tree);
        ThreadPiao t2 = new ThreadPiao("线程2",tree);
        ThreadPiao t3 = new ThreadPiao("线程3",tree);

        t1.start();
        t2.start();
        t3.start();

       try {
            t1.join();//这样可以使线程提前
            t2.join();
            t3.join();
       }catch (InterruptedException e){
            e.printStackTrace();
       }
        System.out.println("~~~~"+tree.value);
    }
}

   线程类,模拟售货员:

import javax.naming.Name;

public class ThreadPiao extends Thread {
    private String name;
    private Tree tree ;
    ThreadPiao(String name, Tree tree) {
        this.name = name;
        this.tree = tree;
    }


    public void run() {// synchronized 不用锁run只锁add ,这样的好处是由于此处没加锁_节省效率,<<只锁调用资源的方法就行>>
        while (tree.value!=0) {

               tree.sale(name);
            try {
                Thread.sleep(10);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

-票

public class Tree {
    int value;

    public synchronized void sale(String name){
            value-=1;
            System.out.println(name+"--->卖了"+"第" + (100 - value) + "张");
        //不是从方法内部声明的变量才需要锁
    }
}
发布了84 篇原创文章 · 获赞 48 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43900387/article/details/104004711