随笔记录
进程、线程、协程
2025-3-28 diaba


1. 进程(Process)




2. 线程(Thread)




3. 协程(Coroutine)




Java中的使用



1. 进程



在Java中,可以通过 Runtime 或 ProcessBuilder 类来创建和管理进程。






import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ProcessExample {
public static void main(String[] args) {
try {
// 创建一个进程
Process process = Runtime.getRuntime().exec("notepad.exe");

// 等待进程结束
int exitCode = process.waitFor();
System.out.println("进程退出码: " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}






2. 线程



在Java中,可以通过继承 Thread 类或实现 Runnable 接口来创建线程。



继承 Thread 类:





public class ThreadExample extends Thread {
@Override
public void run() {
System.out.println("线程正在运行");
}

public static void main(String[] args) {
ThreadExample thread = new ThreadExample();
thread.start(); // 启动线程
}
}









实现 Runnable 接口:





public class RunnableExample implements Runnable {
@Override
public void run() {
System.out.println("线程正在运行");
}

public static void main(String[] args) {
RunnableExample task = new RunnableExample();
Thread thread = new Thread(task);
thread.start(); // 启动线程
}
}









3. 协程



Java本身没有原生的协程支持,但可以通过第三方库(如 Quasar 或 Kotlin 的协程)来实现协程功能。



使用 Quasar 实现协程:





import co.paralleluniverse.fibers.Fiber;
import co.paralleluniverse.fibers.Suspendable;

public class CoroutineExample {
@Suspendable
public static void fiberTask() {
System.out.println("协程正在运行");
}

public static void main(String[] args) {
Fiber<Void> fiber = new Fiber<>(CoroutineExample::fiberTask);
fiber.start(); // 启动协程
fiber.join(); // 等待协程结束
}
}









使用 Kotlin 的协程:





import kotlinx.coroutines.*

fun main() {
GlobalScope.launch {
println("协程正在运行")
}
Thread.sleep(1000) // 等待协程完成
}








总结



在Java中,线程是主要的并发编程工具,而协程可以通过第三方库实现。

发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容