/** * @author * * Lock 是java.util.concurrent.locks下提供的java线程锁,作用跟synchronized类似, * 单是比它更加面向对象,两个线程执行代码段要实现互斥效果,他们需要用同一个Lock, * 锁存在资源类的内部中,而不是存在线程上。 */ public class ThreadLock { public static void main(String[] args) { final Outputer out = new Outputer(); new Thread(new Runnable() { @Override public void run() { while (true) { out.output("duwenlei"); } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { out.output("shenjing"); } } }).start(); } } class Outputer { private Lock lock = new ReentrantLock(); public void output(String name) { lock.lock(); try { //这里必须加try,如果程序抛异常后,锁没有及时打开,程序会出异常 int len = name.length(); for (int i = 0; i < len; i++) { System.out.print(name.charAt(i)); } System.out.println(); } finally { lock.unlock(); } } }