import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockTest { public static void main(String[] args) { new LockTest().init(); } private void init(){ OutPuter outPuter = new OutPuter(); new Thread(new Runnable() { @Override public void run() { while(true){ try { Thread.sleep(10); } catch (Exception e) { e.printStackTrace(); } System.out.println("xiaomama"); } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true){ try { Thread.sleep(10); } catch (Exception e) { e.printStackTrace(); } System.out.println("wychen"); } } }){ }.start(); } static class OutPuter{ Lock lock = new ReentrantLock(); public void output(String name){ int len = name.length(); lock.lock(); try { for(int i=0;i<len;i++){ System.out.println(name.charAt(i)); } System.out.println(); } catch (Exception e) { e.printStackTrace(); }finally{ lock.unlock(); } } } }