Java中创建多线程推荐实现Runnable接口,因其避免单继承限制且更灵活;通过start()启动线程,直接调用run()不创建新线程;控制执行顺序可用join()、wait()/notify()、CountDownLatch等;避免死锁需按序获取锁、使用定时锁或资源排序;线程池大小应根据CPU核心数、任务类型(CPU或IO密集型)合理设置,通常IO密集型设为CPU核心数的2倍,并通过ExecutorService管理线程池。

在Java中,创建和启动多线程主要有两种方式:继承Thread类和实现Runnable接口。选择哪种方式取决于你的具体需求,但通常推荐使用实现Runnable接口的方式,因为它更灵活,避免了Java单继承的限制。
解决方案
继承Thread类:
Thread
run()
run()
Thread
start()
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
thread1.start(); // 启动线程,而不是直接调用run()
}
}直接调用
run()
run()
start()
run()
立即学习“Java免费学习笔记(深入)”;
实现Runnable接口:
Runnable
run()
run()
Runnable
Thread
Runnable
Thread
Thread
start()
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread2 = new Thread(runnable);
thread2.start();
}
}使用
Runnable
控制多线程的执行顺序是一个常见的问题,Java提供了多种机制来实现,例如
join()
wait()
notify()
notifyAll()
CountDownLatch
CyclicBarrier
Semaphore
join()
join()
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 started");
try {
Thread.sleep(1000); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 finished");
});
Thread thread2 = new Thread(() -> {
System.out.println("Thread 2 started");
try {
thread1.join(); // 等待thread1执行完毕
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2 finished");
});
thread1.start();
thread2.start();
}
}在这个例子中,
thread2
thread1
wait()
notify()
notifyAll()
wait()
notify()
notifyAll()
notify()
notifyAll()
synchronized
public class Main {
private static final Object lock = new Object();
private static boolean flag = false;
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 1 started");
try {
while (!flag) {
lock.wait(); // 等待flag变为true
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 finished");
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 2 started");
flag = true;
lock.notify(); // 唤醒等待的线程
System.out.println("Thread 2 finished");
}
});
thread1.start();
try {
Thread.sleep(100); // 确保thread1先启动
} catch (InterruptedException e) {
e.printStackTrace();
}
thread2.start();
}
}在这个例子中,
thread1
thread2
flag
true
CountDownLatch
CountDownLatch
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(2); // 初始化计数器为2
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 started");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 finished");
latch.countDown(); // 计数器减1
});
Thread thread2 = new Thread(() -> {
System.out.println("Thread 2 started");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2 finished");
latch.countDown(); // 计数器减1
});
Thread thread3 = new Thread(() -> {
try {
latch.await(); // 等待计数器变为0
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 3 started after Thread 1 and Thread 2 finished");
});
thread1.start();
thread2.start();
thread3.start();
}
}在这个例子中,
thread3
thread1
thread2
死锁是多线程编程中常见的问题,它指的是两个或多个线程互相等待对方释放资源,导致所有线程都无法继续执行的情况。
避免死锁的一些常见策略:
避免嵌套锁: 尽量避免在一个
synchronized
使用定时锁: 使用
tryLock()
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
private static Lock lock1 = new ReentrantLock();
private static Lock lock2 = new ReentrantLock();
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
try {
if (lock1.tryLock()) {
try {
System.out.println("Thread 1 acquired lock1");
Thread.sleep(100); // 模拟耗时操作
if (lock2.tryLock()) {
try {
System.out.println("Thread 1 acquired lock2");
// 执行操作
} finally {
lock2.unlock();
}
} else {
System.out.println("Thread 1 failed to acquire lock2, releasing lock1");
// 释放lock1
}
} finally {
lock1.unlock();
}
} else {
System.out.println("Thread 1 failed to acquire lock1");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(() -> {
try {
if (lock2.tryLock()) {
try {
System.out.println("Thread 2 acquired lock2");
Thread.sleep(100); // 模拟耗时操作
if (lock1.tryLock()) {
try {
System.out.println("Thread 2 acquired lock1");
// 执行操作
} finally {
lock1.unlock();
}
} else {
System.out.println("Thread 2 failed to acquire lock1, releasing lock2");
// 释放lock2
}
} finally {
lock2.unlock();
}
} else {
System.out.println("Thread 2 failed to acquire lock2");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
thread2.start();
}
}在这个例子中,如果一个线程无法获取所有需要的锁,它会释放已经获取的锁,避免死锁。
使用资源排序: 为所有资源分配一个唯一的编号,线程按照编号的顺序获取资源,避免形成循环等待。
使用死锁检测工具: 一些工具可以帮助检测死锁,例如Java的ThreadMXBean。
线程池的大小对程序的性能有很大的影响。 如果线程池太小,可能会导致任务排队等待,降低程序的响应速度。 如果线程池太大,可能会导致过多的线程切换,增加系统的开销。
选择合适的线程池大小需要考虑多个因素,例如CPU核心数、任务的类型(CPU密集型还是IO密集型)、任务的执行时间等。
CPU密集型任务: 对于CPU密集型任务,线程池的大小可以设置为CPU核心数+1。 额外的线程可以防止CPU在某个线程阻塞时空闲。
IO密集型任务: 对于IO密集型任务,线程池的大小可以设置为CPU核心数的两倍甚至更多。 由于IO操作通常比较耗时,因此需要更多的线程来处理并发的IO请求。
使用Runtime.getRuntime().availableProcessors()
Runtime.getRuntime().availableProcessors()
int cpuCores = Runtime.getRuntime().availableProcessors(); int threadPoolSize = cpuCores * 2; // IO密集型任务
使用ExecutorService
ExecutorService
ThreadPoolExecutor
FixedThreadPool
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
int cpuCores = Runtime.getRuntime().availableProcessors();
int threadPoolSize = cpuCores * 2;
ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
for (int i = 0; i < 10; i++) {
int taskNumber = i;
executor.submit(() -> {
System.out.println("Task " + taskNumber + " running in thread: " + Thread.currentThread().getName());
try {
Thread.sleep(1000); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
executor.shutdown(); // 关闭线程池
}
}在这个例子中,创建了一个固定大小的线程池,线程池的大小是CPU核心数的两倍。
选择合适的线程池大小是一个需要不断尝试和调整的过程。 可以通过监控程序的性能,例如CPU利用率、响应时间等,来调整线程池的大小,以达到最佳的性能。
以上就是java使用教程怎样创建和启动多线程 java使用教程的多线程编程操作技巧的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号