Callable
- 可以有返回值
- 可以抛出异常
- 方法不同 为 call() 方法
callable 的使用
public class CallableTest implements Callable<String> {
@Override
public String call() throws Exception {
return null;
}
}
class Test00{
public static void main(String[] args) {
CallableTest callableTest = new CallableTest();
FutureTask futureTask = new FutureTask(callableTest);
new Thread(futureTask).start();
String str = (String) futureTask.get();
System.out.println(str);
}
}
常用辅助类
CountDownLatch
- countDownLatch.await();//等待归零后再向下执行
- countDownLatch.countDown();//–操作
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i=0;i<6;i++){
new Thread(()->{
System.out.println(Thread.currentThread().getName());
countDownLatch.countDown();
},String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println(countDownLatch.toString());
System.out.println(1111);
}
}
CyclicBarrier
- cyclicBarrier.await(); //等待直到到达new对象时的数字
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("到达7");
});
for(int i=0;i<7;i++){
final int temp = i;
new Thread(()->{
System.out.println("嗨害嗨"+temp+Thread.currentThread().getName());
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
Semaphore
- semaphore.acquire(); //获取 如果满了等待被释放为止
- semaphore.release(); //释放 释放一个线程数
多个共享资源互斥的使用, 并发限流控制最大的线程数
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for(int i =0;i<10;i++){
new Thread(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"到达");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+"离开");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
读写锁 ReadWriteLock
- 读写锁分为读锁和写锁 在写锁时其他写入线程被阻塞
- 读锁 在读取时其他线程可以同时进行读取
public class ReadWriteLockDemo {
public static void main(String[] args) {
ReadWriteLockTest readWriteLockTest = new ReadWriteLockTest();
for (int i = 0; i < 10; i++) {
final int temp = i;
new Thread(()->{
readWriteLockTest.put(temp+" ",temp+"");
},String.valueOf(i)).start();
}
for (int i = 0; i < 10; i++) {
final int temp = i;
new Thread(()->{
readWriteLockTest.get(temp+" ");
},String.valueOf(i)).start();
}
}
}
class ReadWriteLockTest{
private HashMap<String,String> map = new HashMap<>();
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void put(String key,String val){
readWriteLock.writeLock().lock();
System.out.println("写入"+key);
map.put(key,val);
System.out.println("写入"+key+"成功");
readWriteLock.writeLock().unlock();
}
public void get(String key){
readWriteLock.readLock().lock();
map.get(key);
System.out.println("读取成功"+key);
readWriteLock.readLock().unlock();
}
}
|