Java面试必会:多线程编程实例
在Java面试中,多线程编程是一个重要的考察点。以下是一些多线程编程的实例和问题:
创建和启动线程:
- 使用
Thread
类创建新线程。Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 线程内的代码
}
}));
thread.start();
- 使用
同步和互斥:
使用
synchronized
关键字实现线程锁。class Counter {
private int count;
synchronized void increment() {
count++;
notifyAll(); // 通知其他等待的线程
}
synchronized int getCount() {
return count;
}
}
递归和异步:
- 使用
Runnable
或Callable
实现多任务。
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class LongRunningTask implements Runnable {
private int counter;
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
// 线程内的长运行任务代码
counter++;
if (counter == 5) { // 当完成5个循环后,停止并返回结果
System.out.println("Finished after 5 iterations");
return;
}
}
}
}
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {executor.submit(new LongRunningTask());
}
executor.shutdown();
```
以上实例是多线程编程的基础,面试时可能会根据具体需求进行扩展或深入讨论。- 使用
还没有评论,来说两句吧...