线程基础

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

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

你可能感兴趣的:(线程基础)