The thread mutually exclusive synchronized

/**
 * 
 * The thread mutually exclusive, the use of synchronized keyword can achieve mutual exclusion between threads and threads should be noted that if the object on the same synchronized before they can
 * Ensure at the same time, only one thread can execute the synchronized block of code modified
 *
 */
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();
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/moris5013/p/11707452.html