在Java中创建多线程推荐实现Runnable接口,因为它避免了单继承限制,而且更灵活;通过start()启动线程,直接调用Run()不创建新线程;join()可用于控制执行顺序、wait()/notify()、countdownlatch等等;避免按顺序获取锁、使用定时锁或资源排序;线程池的大小应根据CPU的核心数和任务类型(CPU或IO密集型)合理设置。通常,IO密集型设置为CPU核心数的两倍,并通过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()
实际上,方法只在当前线程(main线程)中执行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()
方法: 一个线程可以等待另一个线程完成。例如,线程A调用线程Bjoin()
方法,然后线程A将等待线程B执行完成后再继续执行。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()
方法: 用于线程间通信和同步的Object方法。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
允许一个或多个线程等待其他线程完成操作。它维护一个计数器,初始化为正整数。 当一个线程完成任务时,计数器的值将减少1。 当计数器的值为0时,所有等待线程都会被释放。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()
获取CPU核心数: 可以使用Runtime.getRuntime().availableProcessors()
获取当前系统CPU核心数的方法。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使用教程多线程编程操作技巧的详细内容,请关注图灵教育的其他相关文章!