Java 中并发编程的不同方法
在 Java 中,并发编程是一种允许多个任务或进程在单个处理器或多个处理器上同时运行的技术。它可以提高应用程序的性能和响应能力。然而,它也给 Java 开发人员带来了新的挑战和复杂性,例如同步和死锁。在本文中,我们将探讨一些不同的并发编程方法,例如多线程和执行器。
Java 中的并发编程
Java 的以下三个组件用于并发编程
java.lang.Thread 类
java.lang.Runnable
java.util.concurrent
多线程
它是 Java 编程语言的一项功能,允许我们同时执行多个操作。在其中,操作被分成多个较小的部分,称为线程。每个线程执行一项独立的任务,而不会影响其他线程的性能。多线程的主要好处是可以最佳地利用 CPU 等资源,并提高分配操作的执行时间。
在 Java 中创建线程有两种方法
通过实现 Runnable 接口
通过扩展 Thread 类
在下一个示例中,我们将通过扩展 Thread 类来创建线程
语法
class nameOfThread extends Thread {
// operations
}
方法
创建一个名为"Thrd"的类,并在其中定义一个名为"operation()"的静态方法以及一个参数。
现在,在此方法中,进行一个将运行 4 次的 for 循环,然后增加给定的参数。此循环的 try 块将以指定的时间间隔(即 1000 毫秒)打印输出
进一步,创建三个线程。在这些线程中将参数传递给"operation()"方法。
最后,在主方法中为线程类创建三个对象并使用内置方法"start()"执行它们。
线程示例
以下示例演示了我们到目前为止讨论的有关多线程的内容
class Thrd {
public static void operation(int data) {
for(int i = 1; i <= 4; i++) {
System.out.println(data++);
try {
// each iteration performed with interval of 1 sec
Thread.sleep(1000);
} catch(Exception exp){}
}
}
}
class Thrd1 extends Thread { // thread number 1
public void run() {
Thrd.operation(1);
}
}
class Thrd2 extends Thread { // thread number 2
public void run() {
Thrd.operation(5);
}
}
class Thrd3 extends Thread { // thread number 3
public void run() {
Thrd.operation(10);
}
}
public class ThrdExecution {
public static void main(String args[]) {
// creating object for thread class
Thrd1 oprt1 = new Thrd1();
Thrd2 oprt2 = new Thrd2();
Thrd3 oprt3 = new Thrd3();
// Starting the thread operation
oprt1.start();
oprt2.start();
oprt3.start();
}
}
输出
1 10 5 2 11 6 3 12 7 4 13 8
Executor
它是 Java Concurrent API 的一个接口,可以启动和控制线程执行。它定义了三个预定义类,分别是 ThreadPoolExecutor、ForkJoinPool 和 ScheduledThreadPoolExecutor。这些类进一步实现了 Executor 和 ExecutorService 接口来管理线程。
但是,大多数时候我们使用静态工厂方法来创建由 Executors 实用程序类定义的不同类型的执行器服务 -
newCachedThreadPool()
newFixedThreadPool()
newScheduledThreadPool()
方法
第一步是导入"java.util.concurrent"包以启用 Executor。
现在,除了 main() 方法之外,其余代码的工作原理与第一个示例类似。
在 main() 方法中,使用"newFixedThreadPool()"定义一个执行器并使用其实例和内置方法"execute()"启动线程的执行。
Executor 示例
以下示例说明了 newFixedThreadPool() 与线程的结合使用。
import java.util.concurrent.*;
class Thrd {
public static void operation(int data) {
for(int i = 1; i <= 4; i++) {
System.out.println(data++);
try {
// each iteration performed with interval of 1 sec
Thread.sleep(1000);
} catch(Exception exp){}
}
}
}
class Thrd1 extends Thread { // thread number 1
public void run() {
Thrd.operation(1);
}
}
class Thrd2 extends Thread { // thread number 2
public void run() {
Thrd.operation(5);
}
}
class Thrd3 extends Thread { // thread number 3
public void run() {
Thrd.operation(10);
}
}
public class ThrdExecution {
public static void main(String args[]) {
// creating executer service
ExecutorService es = Executors.newFixedThreadPool(3);
// starting execution
es.execute(new Thrd1());
es.execute(new Thrd2());
es.execute(new Thrd3());
}
}
输出
1 5 10 2 6 11 3 7 12 8 4 13
结论
我们讨论了 Java 中并发编程的各种方法,如线程和执行器。每种方法都有各自的优点和缺点,具体取决于需求。这里,线程是并发的基本单位。
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

