在Java中進行多線程編程可以極大地提高程序的效率和響應性。以下是一個簡要的Java多線程編程指南,涵蓋了多線程的基礎概念、創建方式、線程池的使用以及線程安全與同步機制。
Java線程的生命周期包括:新建(NEW)、可運行(RUNNABLE)、阻塞(BLOCKED)、等待(WAITING)、超時等待(TIMED_WAITING)和終止(TERMINATED)。
class MyThread extends Thread {
public void run() {
System.out.println("線程 " + Thread.currentThread().getName() + " 正在執行");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
class MyRunnable implements Runnable {
public void run() {
System.out.println("線程 " + Thread.currentThread().getName() + " 正在執行");
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
t1.start();
t2.start();
}
}
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> {
TimeUnit.SECONDS.sleep(1);
return 42;
});
System.out.println(future.get());
executor.shutdown();
Executors.newCachedThreadPool()
:彈性線程池Executors.newFixedThreadPool(n)
:固定大小Executors.newSingleThreadExecutor()
:單線程串行Executors.newScheduledThreadPool(n)
:定時任務private final ReentrantLock lock = new ReentrantLock();
public void method() {
lock.lock();
try {
// 臨界區代碼
} finally {
lock.unlock();
}
}
AtomicInteger
以上是一個簡要的Java多線程編程指南,涵蓋了多線程的基礎概念、創建方式、線程池的使用以及線程安全與同步機制。希望這些信息能幫助你更好地理解和實現Java多線程編程。