public class ReentranLockExample {
private static int count = 0;
private static ReentrantLock reentrantLock = new ReentrantLock();
static class MyThread extends Thread{
@Override
public void run() {
super.run();
try {
while (true){
boolean result = reentrantLock.tryLock();
if (result){
System.out.println(Thread.currentThread().getName() + "get the lock success and run the syn code " + count ++);
reentrantLock.unlock();
}else{
System.out.println(Thread.currentThread().getName() + "get the lock failed and run the syn code " + count);
}
System.out.println(Thread.currentThread().getName() + "run the asyntronized code " + count);
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
public class SemaphoreExample {
private static Semaphore semaphore = new Semaphore(2);
private String lock = "lock";
private static int count = 0;
static class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
while (true) {
semaphore.acquire();
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() + "get the lock success and run the syn code " + count++);
semaphore.release();
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
MyThread thread3 = new MyThread();
thread1.start();
thread2.start();
thread3.start();
}
}
public class CountDownLatchExample {
private static CountDownLatch mCountDownLatch = new CountDownLatch(3);
static class MyThread extends Thread {
int awaitTime;
public MyThread(int i) {
this.awaitTime = i;
}
@Override
public void run() {
super.run();
try {
while (true) {
Thread.sleep(awaitTime);
System.out.println(Thread.currentThread().getName() + "arrived " );
mCountDownLatch.countDown();
mCountDownLatch.await(); //可以指定等待时间
System.out.println(Thread.currentThread().getName() + "start meeting " );
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
MyThread thread1 = new MyThread(500);
MyThread thread2 = new MyThread(1000);
MyThread thread3 = new MyThread(2000);
thread1.start();
thread2.start();
thread3.start();
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有