java多线程如何实现
多线程的实现方式
在Java中,多线程可以通过继承Thread类或实现Runnable接口来实现。这两种方式各有优缺点,适用于不同的场景。
继承Thread类需要重写run方法,并通过调用start方法启动线程。这种方式简单直接,但由于Java不支持多重继承,如果类已经继承了其他类,就无法使用这种方式。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现Runnable接口同样需要重写run方法,但需要通过Thread类的构造函数传入Runnable实例来启动线程。这种方式更加灵活,适用于需要实现多继承的场景。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
线程池的使用
线程池是一种高效管理线程的机制,可以避免频繁创建和销毁线程的开销。Java提供了ExecutorService接口及其实现类来支持线程池。
创建固定大小的线程池可以使用Executors.newFixedThreadPool方法。提交任务到线程池后,线程池会自动分配线程执行任务。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
executor.submit(() -> {
System.out.println("Task executed by " + Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
线程同步与锁
多线程环境下,共享资源的访问可能导致数据不一致问题。Java提供了synchronized关键字和Lock接口来保证线程安全。
synchronized可以修饰方法或代码块,确保同一时间只有一个线程访问共享资源。
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());
}
}
Lock接口提供了更灵活的锁机制,例如ReentrantLock。与synchronized相比,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();
}
}
public int getCount() {
return count;
}
}
线程间通信
线程间通信可以通过wait、notify和notifyAll方法实现。这些方法必须在synchronized块或方法内调用。
wait使当前线程进入等待状态,释放锁。notify或notifyAll唤醒等待的线程。
class Message {
private String message;
private boolean empty = true;
public synchronized String read() {
while (empty) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
empty = true;
notifyAll();
return message;
}
public synchronized void write(String message) {
while (!empty) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
empty = false;
this.message = message;
notifyAll();
}
}
高级并发工具
Java并发包(java.util.concurrent)提供了许多高级并发工具,如CountDownLatch、CyclicBarrier、Semaphore等。
CountDownLatch允许一个或多个线程等待其他线程完成操作。
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 done");
}
}
CyclicBarrier允许一组线程互相等待,达到某个公共屏障点后再继续执行。
import java.util.concurrent.CyclicBarrier;
public class Main {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3, () -> {
System.out.println("All threads reached barrier");
});
new Thread(() -> {
try {
System.out.println("Thread 1 reached barrier");
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
System.out.println("Thread 2 reached barrier");
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
System.out.println("Thread 3 reached barrier");
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}






