Java核心内库-线程-线程同步-同步方法

来源:互联网 发布:取消iphone不安全网络 编辑:程序博客网 时间:2024/06/15 23:28

同步方法:
使用synchronized修饰的方法,就叫做同步方法。保证A线程执行该方法的时候,其他线程只能在方法外等着。

synchronized public void doWork(){}

同步锁是谁:
对于非static方法,同步锁就是this
对于static方法,我们使用当前方法所在类的字节码对象(Apple2.class)

class Apple2 implements Runnable{    private int num = 50; //苹果总数    @Override    public void run() {        for (int i=0;i<50;i++){           eat();        }    }    synchronized private void eat(){        if (num>0){            System.out.println(Thread.currentThread().getName()+"吃了编号为"+num+"的苹果");            try {                Thread.sleep(10); // 此时是为了模拟网络延迟            } catch (InterruptedException e) {                e.printStackTrace();            }            num--;        }    }}public class Main {    public static void main(String[] args){        // 创建三个线程(同学)吃苹果        Apple2 a = new Apple2();        new Thread(a,"小A").start();        new Thread(a,"小B").start();        new Thread(a,"小C").start();    }}

synchronized的优劣
好处:保证了多线程并发访问时的同步操作,避免线程安全性问题。
缺点:使用synchronized的方法/代码块 的性能比不使用要低一些。

0 0
原创粉丝点击