1. 创建线程:
Java 提供两种创建线程的方式:
- 继承 Thread 类:
class MyThread extends Thread {
public void run() {
// 线程执行的代码
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value " + i);
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start(); // 启动线程
thread2.start();
}
}
- 实现 Runnable 接口:
class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value " + i);
}
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(new MyRunnable());
thread1.start();
thread2.start();
}
}
2. 同步:
多线程程序可能会面临竞态条件和数据共享的问题,因此需要同步机制。在 Java 中,可以使用 synchronized 关键字来实现同步。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class SynchronizationExample {
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("Count: " + counter.getCount());
}
}
3. 线程池:
线程池可以管理和重用线程,提高程序性能。Java 提供了 Executor 框架来创建线程池。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
// 创建一个固定大小的线程池
ExecutorService executor = Executors.newFixedThreadPool(2);
// 提交任务给线程池
for (int i = 0; i < 5; i++) {
executor.execute(() -> {
System.out.println(Thread.currentThread().getName() + " is executing a task");
});
}
// 关闭线程池
executor.shutdown();
}
}
以上只是 Java 多线程编程的入门示例。多线程编程涉及到更复杂的概念,如线程间通信、锁、条件等。
转载请注明出处:http://www.pingtaimeng.com/article/detail/438/Java