java如何多线程操作
多线程操作基础
在Java中,多线程操作主要通过Thread类和Runnable接口实现。创建线程的方式有两种:继承Thread类或实现Runnable接口。推荐使用Runnable接口,因为Java不支持多重继承,而接口可以避免这一限制。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
线程池管理
直接创建线程可能导致资源浪费和性能问题。使用ExecutorService可以高效管理线程池。Executors类提供了多种线程池创建方法,如固定大小线程池、缓存线程池等。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(new MyRunnable());
}
executor.shutdown();
}
}
同步与锁机制
多线程操作共享资源时,需使用同步机制避免竞态条件。Java提供了synchronized关键字和Lock接口实现线程同步。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.getCount());
}
}
使用volatile关键字
volatile确保变量的可见性,即一个线程修改后,其他线程能立即看到最新值。适用于标记变量或状态标志。
class SharedObject {
private volatile boolean flag = false;
public void setFlag(boolean flag) {
this.flag = flag;
}
public boolean getFlag() {
return flag;
}
}
高级并发工具
Java提供了java.util.concurrent包中的高级工具,如CountDownLatch、CyclicBarrier、Semaphore等,用于复杂线程协作场景。
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3);
new Thread(() -> {
System.out.println("Task 1 done");
latch.countDown();
}).start();
new Thread(() -> {
System.out.println("Task 2 done");
latch.countDown();
}).start();
new Thread(() -> {
System.out.println("Task 3 done");
latch.countDown();
}).start();
latch.await();
System.out.println("All tasks completed");
}
}
使用Future和Callable
Callable接口允许线程返回结果,Future用于获取异步计算结果。适用于需要返回值的多线程任务。

import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> {
Thread.sleep(1000);
return 42;
});
System.out.println("Result: " + future.get());
executor.shutdown();
}
}






