java如何使
使用Java实现多线程
Java中实现多线程可以通过继承Thread类或实现Runnable接口。以下是两种方法的示例:
继承Thread类
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现Runnable接口
class MyRunnable implements Runnable {
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();
}
}
使用线程池
Java提供了ExecutorService来管理线程池,可以更高效地管理多线程任务:
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++) {
Runnable worker = new MyRunnable();
executor.execute(worker);
}
executor.shutdown();
}
}
线程同步
在多线程环境下,可以使用synchronized关键字或Lock接口来保证线程安全:
使用synchronized
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
使用Lock
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private int count = 0;
private Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
线程间通信
使用wait()和notify()方法可以实现线程间的通信:
class SharedResource {
private boolean ready = false;
public synchronized void waitForReady() throws InterruptedException {
while (!ready) {
wait();
}
}
public synchronized void setReady() {
ready = true;
notifyAll();
}
}
使用Future和Callable
Callable接口允许线程返回结果,Future用于获取异步计算的结果:

import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return 42;
}
});
System.out.println(future.get());
executor.shutdown();
}
}






