java 5 Lock

 import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; public class LookTest
{
public static void main(String[] args)
{
runThread("hello");
runThread("world");
} private static void runThread(final String str)
{
new Thread(new Runnable()
{
public void run()
{
// outPut(str);
outPut2(str);
}
}).start();
} private static void outPut(String str)
{
// 使用synchronized对代码加锁
synchronized (LookTest.class)
{
for(int i = 0; i < str.length(); i++)
{
System.out.print(str.charAt(i));
}
System.out.println();
}
} private static Lock lock = new ReentrantLock();
private static void outPut2(String str)
{
// 使用lock锁
lock.lock();
for(int i = 0; i < str.length(); i++)
{
System.out.print(str.charAt(i));
}
System.out.println();
lock.unlock();
}
}

输出结果:

world
hello

上一篇:python之列表及其方法---整理集


下一篇:长轮询和Comet