Java中的多线程机制
Java中的多线程机制允许程序同时执行多个任务,从而提高程序的执行效率和响应速度。Java通过Thread
类和Runnable
接口来实现多线程。
实现多线程的方法
方法一:继承Thread
类
class MyThread extends Thread {
@Override
public void run() {
// 线程执行的代码
System.out.println(" 线程正在运行:" + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start(); // 启动线程1
thread2.start(); // 启动线程2
}
}
方法二:实现Runnable
接口
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
System.out.println(" 线程正在运行:" + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);
thread1.start(); // 启动线程1
thread2.start(); // 启动线程2
}
}
方法三:使用Callable
和Future
import java.util.concurrent.*;
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
// 线程执行的代码
System.out.println(" 线程正在运行:" + Thread.currentThread().getName());
return 42;
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(2);
MyCallable myCallable = new MyCallable();
Future<Integer> future1 = executorService.submit(myCallable);
Future<Integer> future2 = executorService.submit(myCallable);
System.out.println(" 线程1的结果:" + future1.get());
System.out.println(" 线程2的结果:" + future2.get());
executorService.shutdown();
}
}
多线程同步
在多线程编程中,为了保证线程安全,需要对共享资源进行同步访问。Java提供了多种同步机制,如synchronized
关键字和Lock
接口。
使用synchronized
关键字
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(" 计数器的值:" + counter.getCount());
}
}
使用Lock
接口
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private int count = 0;
private final Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(" 计数器的值:" + counter.getCount());
}
}
多线程的并发控制
Java提供了多种并发控制机制,如CountDownLatch
、CyclicBarrier
、Semaphore
等,用于协调多个线程之间的执行顺序和同步操作。
使用CountDownLatch
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException {
int numberOfThreads = 3;
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
new Thread(() -> {
try {
System.out.println(" 线程 " + Thread.currentThread().getName() + " 正在执行");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}).start();
}
latch.await(); // 等待所有线程执行完毕
System.out.println(" 所有线程执行完毕");
}
}
通过理解Java的多线程机制及其实现方法,可以更好地编写高效、安全的并发程序。