线程基础

作者: 小爪哇海 | 来源:发表于2018-10-07 16:27 被阅读0次

    每个对象持有一把锁,两个对象互不干涉

    9E38B53A-028D-4bf0-A994-1F2FEB535DEB.png
    /**
     * @Description TODO
     * @Author "zhouhai"
     * @Date2018/10/716:01
     **/
    public class MultiThread {
    
        private int num = 0;
    
        public synchronized void prinNum(String tag) {
            try {
                if (tag.equals("a")) {
                    num=100;
                    System.out.println("tag a ,set num over!");
                    Thread.sleep(1000);
                }else {
                    num = 200;
                    System.out.println("tag b, set num over!");
                }
                System.out.println("tag"+tag+",num="+num);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) {
            //俩个不同的对象
            final MultiThread m1 = new MultiThread();
            final MultiThread m2 = new MultiThread();
    
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    m1.prinNum("a");
                }
            });
            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    m2.prinNum("b");
                }
            });
    
            t1.start();
            t2.start();
    
    
        }
    
    }
    

    代码运行结果:
    tag a ,set num over!
    tag b, set num over!
    tagb,num=200
    taga,num=100

    相关文章

      网友评论

        本文标题:线程基础

        本文链接:https://www.haomeiwen.com/subject/nyblaftx.html