每日六道java新手入门面试题,通往自由的道路--多线程攻略
简介
本文介绍了如何解决“每日六道java新手入门面试题,通往自由的道路--多线程” 中的六道题目,帮助初学者掌握多线程的概念和使用方法。
题目简介
本题目分为六道题目,主要涉及以下内容:
- 线程的创建和启动
- 共享变量的问题
- 线程安全的问题
- 线程池的概念和使用方法
解题思路
1. 计数器
题目描述:使用两个线程交替打印0-100的数字。
解题思路:可以使用synchronized关键字实现线程同步,利用wait()和notify()方法阻塞和唤醒线程。具体实现可以参考下面的代码示例:
class Counter {
private static final int MAX_VALUE = 100;
private int count = 0;
public synchronized void printNumber() throws InterruptedException {
while (count < MAX_VALUE) {
System.out.println(Thread.currentThread().getName() + ": " + count++);
notify();
wait();
}
notify();
}
}
public class CounterTest {
public static void main(String[] args) {
Counter counter = new Counter();
Runnable r = () -> {
try {
counter.printNumber();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Thread t1 = new Thread(r, "Thread-1");
Thread t2 = new Thread(r, "Thread-2");
t1.start();
t2.start();
}
}
2. 单例模式
题目描述:使用单例模式实现一个线程安全的类。
解题思路:可以使用双重检查锁定(Double-Checked Locking)实现单例模式。具体实现可以参考下面的代码示例:
public class Singleton {
private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
3. 死锁
题目描述:编写一个产生死锁的程序。
解题思路:可以使用两个线程相互等待对方释放锁的方式产生死锁。具体实现可以参考下面的代码示例:
public class Deadlock {
private static final Object LOCK1 = new Object();
private static final Object LOCK2 = new Object();
public static void main(String[] args) {
Runnable r1 = () -> {
synchronized (LOCK1) {
System.out.println(Thread.currentThread().getName() + " holding LOCK1");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (LOCK2) {
System.out.println(Thread.currentThread().getName() + " holding LOCK2");
}
}
};
Runnable r2 = () -> {
synchronized (LOCK2) {
System.out.println(Thread.currentThread().getName() + " holding LOCK2");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (LOCK1) {
System.out.println(Thread.currentThread().getName() + " holding LOCK1");
}
}
};
Thread t1 = new Thread(r1, "Thread-1");
Thread t2 = new Thread(r2, "Thread-2");
t1.start();
t2.start();
}
}
4. 等待通知机制
题目描述:编写程序实现生产者-消费者模型。
解题思路:可以使用等待通知机制实现生产者-消费者模型。具体实现可以参考下面的代码示例:
class Product {
private int id;
public Product(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
class Producer {
private Queue<Product> queue;
private int maxSize;
public Producer(Queue<Product> queue, int maxSize) {
this.queue = queue;
this.maxSize = maxSize;
}
public void produce() throws InterruptedException {
synchronized (queue) {
while (queue.size() == maxSize) {
System.out.println(Thread.currentThread().getName() + " queue is full");
queue.wait();
}
Product product = new Product(queue.size() + 1);
System.out.println(Thread.currentThread().getName() + " produced product " + product.getId());
queue.add(product);
queue.notifyAll();
}
}
}
class Consumer {
private Queue<Product> queue;
public Consumer(Queue<Product> queue) {
this.queue = queue;
}
public void consume() throws InterruptedException {
synchronized (queue) {
while (queue.isEmpty()) {
System.out.println(Thread.currentThread().getName() + " queue is empty");
queue.wait();
}
Product product = queue.poll();
System.out.println(Thread.currentThread().getName() + " consumed product " + product.getId());
queue.notifyAll();
}
}
}
public class ProducerConsumerTest {
public static void main(String[] args) {
Queue<Product> queue = new LinkedList<>();
Producer producer = new Producer(queue, 5);
Consumer consumer = new Consumer(queue);
Runnable r1 = () -> {
for (int i = 0; i < 10; i++) {
try {
producer.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Runnable r2 = () -> {
for (int i = 0; i < 10; i++) {
try {
consumer.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t1 = new Thread(r1, "Producer");
Thread t2 = new Thread(r2, "Consumer");
t1.start();
t2.start();
}
}
5. 线程池
题目描述:编写代码使用线程池实现并行计算。
解题思路:可以使用ExecutorService实现线程池。具体实现可以参考下面的代码示例:
public class ParallelCalculator {
private static final int NUM_THREADS = 4;
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
final int index = i;
Future<Integer> future = executorService.submit(() -> {
return arr[index] * arr[index];
});
futures.add(future);
}
for (Future<Integer> future : futures) {
try {
int result = future.get();
sum += result;
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
executorService.shutdown();
System.out.println("Result: " + sum);
}
}
6. CountDownLatch
题目描述:使用CountDownLatch实现一个主线程等待多个子线程执行完成。
解题思路:可以使用CountDownLatch实现主线程等待多个子线程执行完成。具体实现可以参考下面的代码示例:
public class CountDownLatchTest {
private static final int NUM_THREADS = 4;
private static CountDownLatch countDownLatch = new CountDownLatch(NUM_THREADS);
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; i++) {
executorService.execute(() -> {
System.out.println(Thread.currentThread().getName() + " is running");
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("All threads finished");
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:每日六道java新手入门面试题,通往自由的道路–多线程 - Python技术站