线程互斥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) {
                    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();
        }
    }
}

 

posted @ 2019-10-20 14:08  踏月而来  阅读(129)  评论(0编辑  收藏  举报