zoukankan      html  css  js  c++  java
  • Java 学习笔记之 线程安全

    线程安全:

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

    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,运行结果:

  • 相关阅读:
    网线帘幕动画
    图片缩放/旋转/平移/设置分辨率
    贝塞尔样条
    线性梯度画刷
    画七彩五角星
    kafka安装
    在windows远程提交任务给Hadoop集群(Hadoop 2.6)
    把Spark SQL的metadata存储到mysql
    使用IDEA开发SPARK提交remote cluster执行
    Netty的Channel
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7710062.html
Copyright © 2011-2022 走看看