多线程synchronized用法

来源:互联网 发布:知豆电动汽车四座 编辑:程序博客网 时间:2024/06/18 04:13
package com.x.test;/** * @author lelonta * @version 1.0 */public class threadsynchronized {    public static void main(String[] args) {        //调用init方法        new threadsynchronized().init();    }    public void init() {        //内部类不能在静态方法中创建对象        final Outputer outputer = new Outputer();        //内部类访问局部变量        new Thread(new Runnable() {            @Override            public void run() {                while (true) {                    try {                        Thread.sleep(10);                    } catch (Exception e) {                    }                    outputer.output("hehe");                }            }        }).start();        new Thread(new Runnable() {            @Override            public void run() {                while (true) {                    try {                        Thread.sleep(10);                    } catch (Exception e) {                    }                    outputer.output("haha");                }            }        }).start();    }    class Outputer {        public void output(String name) {            int len = name.length();            synchronized (this) {                //synchronized 实现了代码的互斥                // 及在有线程访问同一个资源的时候另一个线程必须等待                //就如厕所的坑一样 一个人占着 另一个人或者其他人必须等用的人用完才能用                //传的对象必须是唯一的                //name不行 因为name可以传不同的参数                //this 可以防止在外部调用 outputer 的方法不同                //例如 outputer.output("hehe");                //     new Outputer.output("hehe");                for (int i = 0; i < len; i++) {                    System.out.print(name.charAt(i));                }                System.out.println();            }        }    }}
原创粉丝点击