传统线程互斥技术(传统的sychronized)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u014645652/article/details/52124832

在Java中,传统的锁synchronized关键字是用来控制线程同步的,就是在多线程的环境下,控制synchronized代码段不被多个线程同时执行。如果想让同一对象的不同方法互斥,不仅仅要加synchronized,而且锁必须一样:
synchronized(锁){
同步的代码
}

package cn.liuyuan.thread;

public class TraditionalThreadSychronized {
    public static void main(String[] args) {
        new TraditionalThreadSychronized().init();
    }

    public void init() {
        final Outputer outputer = new Outputer();// Outputer内部类
        new Thread(new Runnable() {// 实现Runnable接口
                    @Override
                    public void run() {
                        while (true) {
                            outputer.task01("111111");
                            try {
                                Thread.sleep(10);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                }).start();// 启动线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    outputer.task02("222222");
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
        }).start();// 启动线程
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    Outputer.task03("333333");
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
    }

    static class Outputer {
        public void task01(String name) {
            String xxx = "name";
            // String xxx = new String("name");
            synchronized (Outputer.class) {
                for (int i = 0; i < name.length(); i++) {
                    System.out.print(name.charAt(i));
                }
                System.out.println();
            }
        }

        public void task02(String name) {
            String xxx = "name";
            // String xxx = new String("name");
            synchronized (xxx) {
                for (int i = 0; i < name.length(); i++) {
                    System.out.print(name.charAt(i));
                }
                System.out.println();
            }
        }

            //由static可知synchronized 的锁是(Outputer.class)
        public synchronized static void task03(String name) {
            for (int i = 0; i < name.length(); i++) {
                System.out.print(name.charAt(i));
            }
            System.out.println();
        }
    }
}
展开阅读全文

没有更多推荐了,返回首页