import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* java5中的锁操作
* @author 谭飞
* @date 2012-02-03
*/
public class LockTest {
/**
* @param args
*/
public static void main(String[] args) {
final Outputer outputer = new Outputer();
//线程一
new Thread(new Runnable(){
@Override
public void run() {
while(true)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("tanfei");
}
}}).start();
//线程二
new Thread(new Runnable(){
@Override
public void run() {
while(true)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("feilongjian");
}
}}).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.print(name.charAt(i));
}
System.out.println();
}finally{
lock.unlock();//释放锁,这个应该处于始终执行
}
}
}
}
java5中的锁操作
最新推荐文章于 2023-08-04 14:43:32 发布