并发编程题目怎么写的啊

时间:2025-01-24 00:33:05 游戏攻略

并发编程题目通常涉及多线程、同步、并发集合、线程池等概念。以下是一些常见的并发编程题目及其解答方法:

保证线程执行顺序

题目:如何保证T2在T1执行完后执行,T3在T2执行完后执行?

解答

方法一:使用`Thread.join()`方法实现等待。

```java

public class TestOrder {

public static void main(String[] args) {

Thread thread1 = new Thread(() -> {

try {

sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("thread 1");

});

Thread thread2 = new Thread(() -> {

try {

sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("thread 2");

});

Thread thread3 = new Thread(() -> {

try {

sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("thread 3");

});

thread1.start();

try {

thread1.join();

} catch (InterruptedException e) {

e.printStackTrace();

}

thread2.start();

try {

thread2.join();

} catch (InterruptedException e) {

e.printStackTrace();

}

thread3.start();

}

}

```

方法二:使用`CompletableFuture`的`thenCombine`方法。

```java

import java.util.concurrent.CompletableFuture;

public class TestOrder {

public static void main(String[] args) {

CompletableFuture ft1 = CompletableFuture.supplyAsync(() -> {

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

return "thread 1";

});

CompletableFuture ft2 = ft1.thenCombineAsync(() -> {

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

return "thread 2";

});

CompletableFuture ft3 = ft2.thenCombineAsync(() -> {

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

return "thread 3";

});

System.out.println(ft3.get());

}

}

```

线程安全的计数器类

题目:编写一个线程安全的计数器类,支持并发访问,增加和获取当前值的操作。

解答

使用`AtomicInteger`实现线程安全的计数器。

```java

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadSafeCounter {

private AtomicInteger count = new AtomicInteger(0);

public void increment() {

count.incrementAndGet();

}

public int getCount() {

return count.get();

}

}

```

生产者-消费者模型

题目:设计一个生产者-消费者模型,有一个商品容器类,支持生产者和消费者在不同的线程中运行,当商品容器满时,生产者需要等待直到容器有空位再继续生产,当商品容器为空时,消费者需要等待直到容器中有商品再继续消费。

解答

使用`BlockingQueue`实现线程安全的队列。