首页 > 编程语言 > 详细

Java 学习笔记之 线程安全

时间:2017-10-22 18:19:21      阅读:269      评论:0      收藏:0      [点我收藏+]

线程安全:

 

线程安全的方法一定是排队运行的。

public class SyncObject {
    synchronized public void methodA() {
        try {
            System.out.println("begin methodA threadName = " +
                    Thread.currentThread().getName());
            Thread.sleep(5000);
            System.out.println("end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

public class SyncThreadA extends Thread{
    private SyncObject object;

    public SyncThreadA(SyncObject object) {
        this.object = object;
    }

    @Override
    public void run() {
        super.run();
        object.methodA();
    }
}

public class SyncThreadB extends Thread{
    private SyncObject object;

    public SyncThreadB(SyncObject object) {
        this.object = object;
    }

    @Override
    public void run() {
        super.run();
        object.methodA();
    }
}

public class ThreadRunMain {
    public static void main(String[] args) {
        testSyncThread();
    }
    public static void testSyncThread(){
        SyncObject object = new SyncObject();
        SyncThreadA a = new SyncThreadA(object);
        a.setName("A");
        SyncThreadB b = new SyncThreadB(object);
        b.setName("B");
        a.start();
        b.start();
    }

}

运行结果:

技术分享

如果去掉synchronized,运行结果:

技术分享

 

Java 学习笔记之 线程安全

原文:http://www.cnblogs.com/AK47Sonic/p/7710062.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!