并发编程2 - 同步方法和非同步方法

  • 同步方法只影响其他线程调用同一同步方法,不影响调用其他非同步方法,或其他锁资源的同步方法.

测试代码

public class Test02 {
    Object o = new Object();
    public synchronized void m1() {
        System.out.println("public synchronized void m1 start");
        try {
            Thread.sleep(3000); //睡个三秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("public synchronized void m1 end");
    }

    public void m3() {
        synchronized (o) {
            System.out.println("public m3 start");
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("public m3 end");
        }
    }

    public void m2() {
        System.out.println("public m2 start");
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("public m2 end");
    }

    public static class MyThread implements Runnable {
        int i = 0;
        Test02 t;

        public MyThread(int i, Test02 t) {
            this.i = i;
            this.t = t;
        }

        @Override
        public void run() {
            if(i == 0) {
                this.t.m1();
            }
            if(i == 1) {
                this.t.m2();
            }
            if(i == 2) {
                this.t.m3();
            }
        }
    }

    public static void main(String[] args) {
        Test02 t = new Test02();

        new Thread(new Test02.MyThread(0, t)).start();
        new Thread(new Test02.MyThread(1, t)).start();
        new Thread(new Test02.MyThread(2, t)).start();
    }
}

运行结果

public synchronized void m1 start
public m2 start
public m3 start
public m2 end
public m3 end
public synchronized void m1 end

QA

  • synchronize 锁对象.
  1. 尽量自己定义一个Object对象.如果使用this的话比较重量级,效率低.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值