首页 > 编程语言 > 详细

线程互斥synchronized

时间:2019-10-20 15:35:19      阅读:64      评论:0      收藏:0      [点我收藏+]
/**
 * 
 * 线程互斥,采用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) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    output.print("zhangsan");
                }
            };
        }.start();

        new Thread() {

            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    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();
        }
    }
}

 

线程互斥synchronized

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

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