public class TraditionalThreadTest { static class Outputer { public void output1(String name) { synchronized (Outputer.class) { for (int i = 0; i < name.length(); i++) { System.out.print(name.charAt(i)); } System.out.println(); } } public synchronized void output2(String name) { for (int i = 0; i < name.length(); i++) { System.out.print(name.charAt(i)); } System.out.println(); } public static synchronized void output3(String name) { for (int i = 0; i < name.length(); i++) { System.out.print(name.charAt(i)); } System.out.println(); } } public static void main(String[] args) { new TraditionalThreadTest().init(); } private void init() { final Outputer outputer = new Outputer(); new Thread(new Runnable() { @Override public void run() { while (true) { outputer.output1("111111111111111"); } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { outputer.output2("0000000000000000000"); } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { outputer.output3("2222222222222222222"); } } }).start(); } }
synchronized用法的一个实例,布布扣,bubuko.com
原文地址:http://blog.csdn.net/ro_wsy/article/details/26496771