freeCodeCamp/guide/chinese/java/multithreading/index.md

35 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

---
title: Multithreading
localeTitle: 多线程
---
## 多线程
多线程是一个同时执行多个进程的过程。 Java使用主线程启动程序并且只要有任何用户创建它就会在主线程上添加更多线程。主线程是任何Java程序中的第一个用户线程。此外JVM确保在程序结束之前关闭所有用户线程。
线程既有优点也有缺点。
## 好处:
* 独立于其他线程运行代码。
* 创建模块化设计。
## 缺点:
如果线程未正确同步,则会出现竞争条件和死锁。
线程可以进一步分为两类:
* 用户线程
* 守护线程
可以通过两种方式创建线程:
1. 实现Runnable接口 Runnable接口中只有一个方法即public void run。实现此方法将确保每当此线程启动时run内的代码执行。
2. 扩展线程类。 这个类还包含public void run为了运行我们自己的代码我们需要覆盖它们。使用此方法的缺点是我们在Thread中有一个超类并且不能扩展我们可能想要的任何其他类。
两者的代码可以在这里找到http//ide.geeksforgeeks.org/k7GjcA。
您会注意到,如果多次运行此代码,结果可能会有所不同。这是由运行它的操作系统决定的。操作系统可以从可运行状态中选择任何线程并运行它。我们没有控制权。如果有多个线程处于可运行状态(准备运行),则可以挑选任何人。它甚至不依赖于优先权。
更多详情https//www.ntu.edu.sg/home/ehchua/programming/java/J5e\_multithreading.html