public interface Lock{
void lock(); //加锁
//优先考虑响应中断,而不是响应锁定的普通获取或重入获取
void lockInterruptibly() throws InterruptedException;
boolean tryLock(); //可定时和可轮询的锁获取模式
boolean tryLock(long timeout,TimeUnit unit) throws InterruptedException;
void unlock(); //解锁
Condition newCondition();
}
package com.ljq.test.thread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 用Lock替代synchronized
*
* @author Administrator
*
*/
public class LockTest {
public static void main(String[] args) {
new LockTest().init();
}
private void init() {
final Outputer outputer = new Outputer();
//A线程
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("zhangsan");
}
}
}).start();
//B线程
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("lisi");
}
}
}).start();
}
static class Outputer {
Lock lock = new ReentrantLock();
/**
* 打印字符
*
* @param name
*/
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();
}
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有