当前位置:网站首页>阿里一个面试题:使用两个线程,交替输出字母和数字
阿里一个面试题:使用两个线程,交替输出字母和数字
2022-06-27 12:10:00 【wgslucky】

- 使用LockSupport
LockSupport类,是JUC包中的一个工具类,是用来创建锁和其他同步类的基本线程阻塞原语。
LockSupport类的核心方法有两个:park()和unpark(),其中park()方法用来阻塞当前调用线程,unpark()方法用于唤醒指定线程。这其实和Object类的wait()和singal()方法有些类似,但是LockSupport的这两种方法从语义上将比Object类的方法更清晰,而且可以针对指定线程进行阻塞和唤醒。
/** * @author 王广帅 * @since 2022/6/26 11:01 */
public class LockSupportDemo {
static Thread t1 = null;
static Thread t2= null;
public static void main(String[] args) {
char[] charArray1 = "123456789".toCharArray();
char[] charArray2 = "ABCDEFGHI".toCharArray();
t1 = new Thread(()->{
for(char c : charArray1){
System.out.print(c);
// 叫醒线程t2
LockSupport.unpark(t2);
// 当前线程阻塞
LockSupport.park();
}
},"线程1");
t2 = new Thread(()->{
for(char c : charArray2){
// 阻塞当前线程
LockSupport.park();
System.out.print(c);
// 叫醒线程t1
LockSupport.unpark(t1);
}
},"线程2");
t1.start();
t2.start();
}
}
- 使用wait,notify
注意wait,notify必须在锁里面执行
/** * @author 王广帅 * @since 2022/6/26 11:12 */
public class WaitNotifyDemo {
public static void main(String[] args) {
final Object obj = new Object();
char[] charArray1 = "123456789".toCharArray();
char[] charArray2 = "ABCDEFGHI".toCharArray();
new Thread(()->{
synchronized (obj) {
for (char c : charArray1) {
System.out.print(c);
try {
obj.notify();
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
obj.notify();
}
},"线程1").start();
new Thread(()->{
synchronized (obj) {
for (char c : charArray2) {
System.out.print(c);
try {
obj.notify();
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
obj.notify();
}
},"线程2").start();
}
}
- 使用Lock Condition
/** * @author 王广帅 * @since 2022/6/26 13:26 */
public class LockConditionDemo {
public static void main(String[] args) {
char[] charArray1 = "123456789".toCharArray();
char[] charArray2 = "ABCDEFGHI".toCharArray();
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2= lock.newCondition();
new Thread(()->{
lock.lock();
try{
for(char c: charArray1){
System.out.print(c);
condition2.signal();
condition1.await();
}
condition2.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
},"线程1").start();
new Thread(()->{
lock.lock();
try{
for(char c: charArray2){
System.out.print(c);
condition1.signal();
condition2.await();
}
condition1.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
},"线程2").start();
}
}
- 使用TransferQueue
TransferQueue(java7引入)继承了BlockingQueue(BlockingQueue又继承了Queue)并扩展了一些新方法。生产者会一直阻塞直到所添加到队列的元素被某一个消费者所消费(不仅仅是添加到队列里就完事)。
/** * @author 王广帅 * @since 2022/6/26 13:49 */
public class TransferQueueDemo {
public static void main(String[] args) {
char[] charArray1 = "123456789".toCharArray();
char[] charArray2 = "ABCDEFGHI".toCharArray();
TransferQueue<Character> queue = new LinkedTransferQueue<>();
new Thread(()->{
try{
for(char c : charArray1){
System.out.print(queue.take());
queue.transfer(c);
}
}catch (Exception e){
e.printStackTrace();
}
},"线程1").start();
new Thread(()->{
try{
for(char c: charArray2){
queue.transfer(c);
System.out.print(queue.take());
}
}catch (Exception e){
e.printStackTrace();
}
},"线程2").start();
}
}
以上示例来自马士兵老师的课程
边栏推荐
- 解除百度文库VIP、语雀、知乎付费限制,原来这么简单
- Uniapp drop-down layer selection box effect demo (sorting)
- 面试突击60:什么情况会导致 MySQL 索引失效?
- mysql学习1:安装mysql
- uni-app 使用escook/request-miniprogram插件发请求说明
- Picocli getting started
- Object serialization
- Write it down once Net analysis of a property management background service stuck
- LeetCode_快速幂_递归_中等_50.Pow(x, n)
- pull request
猜你喜欢

JMeter connection DM8

What's the matter with Amazon's evaluation dropping and failing to stay? How to deal with it?

How to find the movie and TV clips with the same lines? These 8 movies search for artifact, and find the corresponding segment in one line

秒云荣获《2022爱分析 · IT运维厂商全景报告》智能运维AIOps市场代表厂商

ACL 2022 | 中科院提出TAMT:TAMT:通过下游任务无关掩码训练搜索可迁移的BERT子网络

esp32s3 IPERF例程测试 esp32s3吞吐量测试

The world's fastest download tool XDM

微服务拆分

Topic37——64. 最小路径和

本地可视化工具连接阿里云centOS服务器的redis
随机推荐
In 2021, the global professional liability insurance revenue was about USD 44740million, and it is expected to reach USD 55980million in 2028. From 2022 to 2028, the CAGR was 3.5%
How to participate in openharmony code contribution
picocli-入门
A brief talk on cordola tree
Dm8: Dameng database - lock timeout
Private dry goods sharing: how to implement platform in Enterprise Architecture
如何修改 node_modules 里的文件
Nifi from introduction to practice (nanny level tutorial) - identity authentication
nifi从入门到实战(保姆级教程)——身份认证
浅谈珂朵莉树
Uniapp drop-down layer selection box effect demo (sorting)
. Net6 access skywalking link tracking complete process
pull request
This privatized deployed enterprise knowledge base makes telecommuting a zero distance
hibernate操作oracle数据库 主键自增
What's the matter with Amazon's evaluation dropping and failing to stay? How to deal with it?
Histrix工作原理
Word text box page feed
Getting started with go web programming: validators
ACL 2022 | 中科院提出TAMT:TAMT:通过下游任务无关掩码训练搜索可迁移的BERT子网络