public class SynchronizedClass {
public synchronized void syncMethod(){
//代码
}
public void syncThis(){
synchronized (this){
//代码
}
}
public void syncClassMethod(){
synchronized (SynchronizedClass.class){
//代码
}
}
public synchronized static void syncStaticMethod(){
//代码
}
}
public class ReentrantLockDemo {
Lock lock = new ReentrantLock();
public void doSth(){
lock.lock();
try {
//执行某些操作
}finally {
lock.unlock();
}
}
}
public class MyArrayBlockingQueue<T> {
// 数据数组
private final T[] items;
private final Lock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition() ;
// 头部索引
private int head;
// 尾部索引
private int tail ;
// 数据的个数
private int count;
public MyArrayBlockingQueue(int maxSize) {
items = (T[]) new Object[maxSize];
}
public MyArrayBlockingQueue(){
this(10);
}
public void put(T t){
lock.lock();
try {
while(count == getCapacity()){
System.out.println("数据已满,等待");
notFull.await();
}
items[tail] =t ;
if(++tail ==getCapacity()){
tail = 0;
}
++count;
notEmpty.signalAll();//唤醒等待数据的线程
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public int getCapacity(){
return items.length ;
}
public T take(){
lock.lock();
try {
while(count ==0){
System.out.println("还没有数据,等待");
//哪个线程调用await()则阻塞哪个线程
notEmpty.await();
}
T ret = items[head];
items[head] = null ;
if(++head == getCapacity()){
head =0 ;
}
--count;
notFull.signalAll();
return ret ;
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
return null ;
}
public int size(){
lock.lock();
try {
return count;
}finally {
lock.unlock();
}
}
public static void main(String[] args){
MyArrayBlockingQueue<Integer> aQueue = new MyArrayBlockingQueue<>();
aQueue.put(3);
aQueue.put(24);
for(int i=0;i<5;i++){
System.out.println(aQueue.take());
}
System.out.println("结束");
}
}
public class SemaphoreTest {
public static void main(String[] args){
final ExecutorService executorService = Executors.newFixedThreadPool(3);
final Semaphore semaphore = new Semaphore(3);
List<Future> futures = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Future<?> submit = executorService.submit(new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(" 剩余许可: " + semaphore.availablePermits());
Thread.sleep(3000);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
futures.add(submit);
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有