多线程编程:Java并发编程详解
大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!今天我们来深入探讨一下Java的多线程编程和并发编程。
1. 多线程基础
多线程是指在一个程序中同时运行多个线程,线程是轻量级的进程,能够实现并发执行。Java提供了多种方式来创建和管理线程。
1.1 使用Thread类
通过继承Thread类并重写其run方法,可以创建一个新的线程。
package cn.juwatech.concurrency;
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
1.2 使用Runnable接口
实现Runnable接口,并将其实例传递给Thread对象。
package cn.juwatech.concurrency;
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable is running");
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
1.3 使用Callable接口
Callable接口类似于Runnable,但它可以返回结果并且可以抛出异常。
package cn.juwatech.concurrency;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return 123;
}
public static void main(String[] args) {
MyCallable callable = new MyCallable();
FutureTask<Integer> futureTask = new FutureTask<>(callable);
Thread thread = new Thread(futureTask);
thread.start();
try {
Integer result = futureTask.get();
System.out.println("Callable result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
2. 线程同步
在多线程编程中,同步是一个关键概念,用于防止多个线程同时访问共享资源而导致的数据不一致。
2.1 使用synchronized关键字
synchronized关键字用于锁定一个对象,使得在同一时刻只有一个线程可以访问该对象的同步代码块或方法。
package cn.juwatech.concurrency;
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
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("Final count: " + counter.getCount());
}
}
2.2 使用显式锁(ReentrantLock)
ReentrantLock是一个显式的锁对象,可以替代synchronized关键字提供更多的锁控制。
package cn.juwatech.concurrency;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockExample {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
ReentrantLockExample example = new ReentrantLockExample();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final count: " + example.getCount());
}
}
3. 线程通信
Java提供了多种机制来实现线程间的通信,如wait(), notify()和notifyAll()方法。
3.1 使用wait()和notify()
wait()和notify()方法用于在线程之间进行协调和通信。它们必须在同步块中使用。
package cn.juwatech.concurrency;
public class WaitNotifyExample {
private final Object lock = new Object();
private boolean ready = false;
public void produce() throws InterruptedException {
synchronized (lock) {
System.out.println("Producing...");
ready = true;
lock.notify();
}
}
public void consume() throws InterruptedException {
synchronized (lock) {
while (!ready) {
lock.wait();
}
System.out.println("Consuming...");
}
}
public static void main(String[] args) throws InterruptedException {
WaitNotifyExample example = new WaitNotifyExample();
Thread producer = new Thread(() -> {
try {
Thread.sleep(1000); // Simulate some work
example.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread consumer = new Thread(() -> {
try {
example.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
consumer.start();
producer.start();
consumer.join();
producer.join();
}
}
4. 并发容器
Java提供了一些线程安全的并发容器类,如ConcurrentHashMap、CopyOnWriteArrayList等。
4.1 使用ConcurrentHashMap
ConcurrentHashMap是线程安全的哈希表,实现了高效的并发访问。
package cn.juwatech.concurrency;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentHashMapExample {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
ExecutorService executor = Executors.newFixedThreadPool(2);
Runnable task1 = () -> {
for (int i = 0; i < 1000; i++) {
map.put("key" + i, i);
}
};
Runnable task2 = () -> {
for (int i = 0; i < 1000; i++) {
map.put("key" + (i + 1000), i);
}
};
executor.submit(task1);
executor.submit(task2);
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Map size: " + map.size());
}
}
4.2 使用CopyOnWriteArrayList
CopyOnWriteArrayList是线程安全的ArrayList,通过复制数组来实现写操作的并发控制。
package cn.juwatech.concurrency;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListExample {
public static void main(String[] args) throws InterruptedException {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
list.add("item" + i);
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
list.add("item" + (i + 1000));
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("List size: " + list.size());
}
}
5. 高级并发工具
Java的并发包还提供了一些高级的工具类,如CountDownLatch、CyclicBarrier和Semaphore等。
5.1 使用CountDownLatch
CountDownLatch允许一个或多个线程等待,直到在其他线程中执行的一组操作完成。
package cn.juwatech.concurrency;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int threadCount = 3;
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
new Thread(new Worker(latch)).start();
}
latch.await(); // Main thread waits until all workers are done
System.out.println("All workers are done.");
}
static class Worker implements Runnable {
private final CountDownLatch latch;
Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
System.out.println("Working...");
Thread.sleep(1000); // Simulate work
} catch (Interrupted
Exception e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
}
}
本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!