线程互斥synchronized

时间:2019-10-20
本文章向大家介绍线程互斥synchronized,主要包括线程互斥synchronized使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
/**
 * 
 * 线程互斥,采用synchronized关键字可以实现线程与线程之间的互斥,要注意的是在synchronized上的对象要是同一个,才可以
 * 保证在同一时刻,只有一个线程可以执行被synchronized修饰的代码块
 *
 */
public class SynchronizedTest {

    public static void main(String[] args) {
        new SynchronizedTest().print();
    }

    public void print() {
        Output output = new Output();
        new Thread() {

            @Override
            public void run() {
                while (true) {
                    output.print("zhangsan");
                }
            };
        }.start();

        new Thread() {

            @Override
            public void run() {
                while (true) {
                    output.print("wangwu");
                }
            };
        }.start();
    }

    class Output {
        
        synchronized void print(String name) {
            int len = name.length();
            for (int i = 0; i < len; i++) {
                System.out.print(name.charAt(i));
            }
            System.out.println();
        }
    }
}

原文地址:https://www.cnblogs.com/moris5013/p/11707452.html