主要技能和概念
• 了解创建多线程的基础知识
• 了解 Thread 类和 Runnable
接口
• 创建一个线程
• 创建多个线程
• 确定线程何时结束
• 使用线程优先级
• 了解线程同步
• 使用同步方法
• 使用同步块
• 促进线程之间的通信
• 暂停、恢复和停止线程
线程:这些是程序内独立的执行路径。
多任务:它可以基于进程(多个程序)或线程(同一程序中的多个任务)。
优点:
利用空闲时间提高效率。
更好地利用多核/多处理器系统。
线程创建和管理
类和接口:
Thread:封装线程的类。
Runnable:用于定义自定义线程的接口。
常用线程类方法:
创建主题:
class MyThread implements Runnable { String threadName; MyThread(String name) { threadName = name; } public void run() { System.out.println(threadName + " starting."); try { for (int i = 0; i <p>预期输出:<br> </p> <pre class="brush:php;toolbar:false">Main thread starting. . Child #1 starting. .. In Child #1, count is 0 ... In Child #1, count is 1 ... Main thread ending.
线程类扩展:
class MyThread extends Thread { MyThread(String name) { super(name); } public void run() { System.out.println(getName() + " starting."); try { for (int i = 0; i <p>注意:sleep()方法使得调用它的线程暂停执行<br> 在指定的毫秒时间内。</p> <p>书桌<br> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173222510810234.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Cap Programação com várias threads"></p>
以上是多线程 Cap 编程的详细内容。更多信息请关注PHP中文网其他相关文章!