欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Callable应用与常用的辅助类

程序员文章站 2022-03-26 11:15:46
1.Callable应用CallableTest.javapackage callable;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;public class CallableTest {public static void main(String[] args) throws...

1.Callable应用

CallableTest.java

package callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableTest {

	public static void main(String[] args) throws InterruptedException, ExecutionException {

//		new Thread(new Runnable()).start();
//		new Thread(new FutureTask<>()).start();
//		new Thread(new FutureTask<>(callable)).start();
		
		new Thread().start();
		MyThread thread=new MyThread();
//		适配类
		FutureTask futureTask = new FutureTask(thread);
		new Thread(futureTask,"A").start();
		new Thread(futureTask,"B").start();
		
//		这个方法可能会产生阻塞
		Integer o = (Integer) futureTask.get();
		System.out.println(o);
		
	}
}

class MyThread implements Callable<Integer> {

	@Override
	public Integer call() throws Exception {
		System.out.println("call()");
//		耗时的操作
		return 1024;
	}

}

 控制台

call()
1024
  • 缓存
  • 结果可能需要等待,会阻塞

2. CountDownLatch应用

CountDownLatchDemo.java

package add;

import java.util.concurrent.CountDownLatch;

//计数器
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()+" GO OUT");
//				数量-1
				countDownLatch.countDown();
			},String.valueOf(i)).start();
		}
		
//		等待计数器归零,然后向下执行
		countDownLatch.await();
		
		System.out.println("Door Close");
	}
}

控制台

0 GO OUT
1 GO OUT
4 GO OUT
2 GO OUT
3 GO OUT
5 GO OUT
Door Close

每次有线程调用countDown(),数量-1,假设计数器变为0,countDownLatch.await()就会被唤醒,继续执行


3.CyclicBarrier应用 

CyclicBarrierDemo.java

package add;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {

	public static void main(String[] args) {
		/**
		 * 集齐7颗龙珠召唤神龙
		 */

		CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
			System.out.println("成功召唤神龙");
		});

		for (int i = 0; i < 7; i++) {

			final int temp=i;
//			lambda表达式
			new Thread(() -> {
				System.out.println(Thread.currentThread().getName()+"收集"+temp+"个龙珠");
//				等待
				try {
					cyclicBarrier.await();
				} catch (InterruptedException | BrokenBarrierException e) {
					e.printStackTrace();
				}
			}).start();
		}
	}
}

控制台

Thread-2收集2个龙珠
Thread-1收集1个龙珠
Thread-0收集0个龙珠
Thread-3收集3个龙珠
Thread-4收集4个龙珠
Thread-5收集5个龙珠
Thread-6收集6个龙珠
成功召唤神龙

  


 4.Semaphore应用

SemaphoreDemo.java

package add;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {

	public static void main(String[] args) {
//		线程数量:停车位
		Semaphore semaphore = new Semaphore(3);

		for (int i = 1; i <= 6; i++) {
			new Thread(() -> {

				try {
//					得到
					semaphore.acquire();
					System.out.println(Thread.currentThread().getName()+"抢到车位");
//					休眠
					TimeUnit.SECONDS.sleep(2);
					System.out.println(Thread.currentThread().getName()+"离开车位");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}finally {
//					释放
					semaphore.release();
				}
			},String.valueOf(i)).start();
		}
	}
}

控制台

1抢到车位
2抢到车位
3抢到车位
1离开车位
2离开车位
4抢到车位
3离开车位
5抢到车位
6抢到车位
5离开车位
4离开车位
6离开车位
  • semaphore.acquire():获得,如果已经满了,等待被释放为止
  • semaphore.release():释放,将当前的信号量释放+1,唤醒等待的线程

作用:多个共享资源互斥的使用,并发限流,控制最大的线程数!

本文地址:https://blog.csdn.net/weixin_44364444/article/details/110008263

相关标签: java