Java 从入门到精通(续集20)——多线程编程

news/2025/2/13 6:08:17/

Java 从入门到精通(续集20)——多线程编程

Java 中的多线程编程是指通过使用 Java 提供的各种多线程 API 和机制来实现多个线程之间的并发执行。Java 中主要使用的多线程技术包括 Thread、Runnable、Executor、ThreadPool、Lock、Semaphore、CountDownLatch 等。

一、Thread 和 Runnable

Java 中的 Thread 和 Runnable 是最基本的多线程 API,可以通过继承 Thread 类或实现 Runnable 接口来创建多个线程。

示例代码:

class MyThread extends Thread {public void run() {System.out.println("Thread " + Thread.currentThread().getId() + " is running.");}
}class MyRunnable implements Runnable {public void run() {System.out.println("Thread " + Thread.currentThread().getId() + " is running.");}
}public static void main(String[] args) {MyThread thread1 = new MyThread();MyThread thread2 = new MyThread();thread1.start();thread2.start();MyRunnable runnable = new MyRunnable();Thread thread3 = new Thread(runnable);Thread thread4 = new Thread(runnable);thread3.start();thread4.start();
}

二、Executor 和 ThreadPool

Java 中的 Executor 和 ThreadPool 是一种更高层次的多线程机制,可以通过 ExecutorService 来管理线程池和任务队列,从而实现更加灵活和高效的线程处理。

示例代码:

class MyTask implements Runnable {public void run() {System.out.println("Task " + Thread.currentThread().getId() + " is running.");}
}public static void main(String[] args) {ExecutorService executor = Executors.newFixedThreadPool(2);for (int i = 0; i < 10; i++) {executor.execute(new MyTask());}executor.shutdown();while (!executor.isTerminated()) {Thread.yield();}System.out.println("All tasks are finished.");
}

三、Lock 和 Condition

Java 中的 Lock 和 Condition 是一种更加灵活和高度封装的多线程机制,可以通过 ReentrantLock 和 Condition 来实现更精细的线程同步和通信操作。

示例代码:

class MyQueue {private Lock lock = new ReentrantLock();private Condition full = lock.newCondition();private Condition empty = lock.newCondition();private Queue<String> queue = new LinkedList<>();private int maxSize = 10;public void put(String item) throws InterruptedException {try {lock.lock();while (queue.size() == maxSize) {full.await();}queue.offer(item);empty.signalAll();} finally {lock.unlock();}}public String take() throws InterruptedException {try {lock.lock();while (queue.isEmpty()) {empty.await();}String item = queue.poll();full.signalAll();return item;} finally {lock.unlock();}}
}public static void main(String[] args) {MyQueue queue = new MyQueue();new Thread(() -> {for (int i = 0; i < 20; i++) {try {queue.put("item-" + i);System.out.println("put item-" + i);Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}).start();new Thread(() -> {for (int i = 0; i < 20; i++) {try {String item = queue.take();System.out.println("take " + item);Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}}).start();
}

以上就是 Java 中的多线程编程,通过使用 Thread、Runnable、Executor、ThreadPool、Lock、Condition 等机制可以实现更加灵活和高效的多线程操作。在实际开发中,要注意同步和通信等问题,并尽可能地使用线程池、锁、信号量、闭锁等技术来提高性能和可靠性。下一篇续集将为您介绍 Java 中的反射和注解。


http://www.ppmy.cn/news/496329.html

相关文章

java入门2(运算符)

目录 运算符和C语言基本一样 算术运算符 单目运算符&#xff1a;自增自减运算符 比较运算符 逻辑运算符 位运算符&#xff08;C语言好像没有&#xff09; 优先级 交换算法 运算符和C语言基本一样 算术运算符 比如拆分一个三位数 public class java练习代码 {public…

图片加载错误的捕获及处理

引言 前端开发中&#xff0c;图片是我们在网页中加载最多的静态资源类型之一&#xff0c;但是图片加载过程中也有可能出现加载失败的情况&#xff0c;这是十分影响用户体验的。那么如何正确的判断图片是否成功加载&#xff0c;以及图片加载失败的时候&#xff0c;如何处理&…

什么是HTTP 500内部服务器错误,要怎么修复

HTTP 500是一种原始的错误代码&#xff0c;它指示网站服务器在处理请求时发生了内部错误&#xff0c;不过具体错误原因是不确定的。一般情况下&#xff0c;这种错误通常是由服务器程序上的bug或者配置问题造成的。当服务器收到请求时&#xff0c;尝试执行它时&#xff0c;但是发…

Spring FrameWork从入门到NB -@primary、@Qualifier、@Resource@Value

学习几个非常常用的但是也非常简单的Spring注解。只是做个简单说明&#xff0c;具体可参考Spring官网&#xff0c;说的很详细。 Primary 其实前面几篇文章已经做过了解了&#xff0c;我们知道Spring自动装配的时候首先是按类型获取候选对象的&#xff0c;那就有可能有多个对象…

Ubuntu 普通用户赋予管理员权限

1. 使用root权限修改 /etc/sudoers 文件 2.假设为普通用户liu添加管理员权限在文件底部添加一行liu ALL(ALL:ALL) ALL 3.wq!保存退出 4. 普通用户sudo -i 切换root用户&#xff0c;没有提示输入密码

安装百度网盘 系统权限限制

亲测有效&#xff0c;分享给大家~~ 选好自己要安装的路径将这个路径全选复制下来点击 “返回默认路径” 按钮再将复制的路径重新粘贴进去把最前边大写的盘符C改成小写c成了&#xff01;

Linux系统中限制用户su-权限的方法

为了更进一步加强系统的安全性&#xff0c;有必要建立一个管理员的 组&#xff0c;只允许这个组的用户来执行“su -”命令登录为root用户&#xff0c;而让其他组的用户即使执行“su -”、输入了正确的root密码&#xff0c;也无法登录为root用户。在UNIX和Linux下&#xff0c;这…

系统篇:给普通用户赋予 root 权限

切换到root用户 su给/etc/sudoers文件增加写权限 chmod w /etc/sudoers编辑/etc/sudoers文件 vim /etc/sudoers比如要给zs用户赋予root权限 找到 root ALL(ALL) ALL的字段,在下一行追加&#xff1a;zs ALL(ALL) ALL恢复/etc/sudoers文件权限 chmod -w /etc/sudoers此时zs用…