Ubuntu下Java多线程编程技巧
在Ubuntu系统中,Java多线程编程的核心逻辑与Windows、macOS等系统一致,均基于Java语言提供的多线程机制(如Thread类、Runnable接口、java.util.concurrent包)。以下是针对Ubuntu环境的具体技巧与实践建议:
Runnable接口并重写run()方法,避免Java单继承的限制,更适合资源共享的场景。例如:class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
ExecutorService管理线程生命周期,避免频繁创建/销毁线程的开销。Ubuntu环境下,可根据CPU核心数设置线程池大小(如Runtime.getRuntime().availableProcessors()),提升资源利用率。例如:import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for (int i = 0; i < 10; i++) {
executor.submit(() -> System.out.println(Thread.currentThread().getName() + " is running"));
}
executor.shutdown();
}
}
class Counter {
private int count = 0;
public synchronized void increment() { // 同步方法
count++;
}
public int getCount() { return count; }
}
finally块中调用unlock())。例如: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();
}
}
}
import java.util.concurrent.CountDownLatch;
class Worker extends Thread {
private final CountDownLatch latch;
Worker(CountDownLatch latch) { this.latch = latch; }
@Override
public void run() {
try { Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + " done"); }
catch (InterruptedException e) { e.printStackTrace(); }
finally { latch.countDown(); }
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
int numWorkers = 3;
CountDownLatch latch = new CountDownLatch(numWorkers);
for (int i = 0; i < numWorkers; i++) new Worker(latch).start();
latch.await(); // 主线程等待所有Worker完成
System.out.println("All workers done");
}
}
Collections.synchronizedMap,提供更高的并发性能。例如:import java.util.concurrent.ConcurrentHashMap;
public class Main {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key1", 1);
map.put("key2", 2);
System.out.println(map.get("key1")); // 输出1
}
}
CPU核心数+1,I/O密集型任务(如网络请求)建议设置为2*CPU核心数。ThreadPoolExecutor.CallerRunsPolicy拒绝策略,当线程池满时由调用线程执行任务,防止任务堆积。// 统一锁顺序避免死锁
synchronized (lockA) {
synchronized (lockB) { /* 业务逻辑 */ }
}
-Xms、-Xmx)和垃圾回收策略(如-XX:+UseG1GC),提升多线程程序性能。例如:java -Xms512m -Xmx1024m -XX:+UseG1GC -jar YourApp.jar
VisualVM、JProfiler监控Ubuntu下Java进程的线程状态(如阻塞、等待),定位性能瓶颈。