【2023级】智能医学工程专业-计算机程序设计-第11章-多线程
作者: 阮晓龙 发布时间: 2024/9/13 13:19:10
基本信息:
章节名称:智能医学工程专业-计算机程序设计-第11章-多线程
授课教师:信息技术学院互联网技术教学团队
完成时间:2024年09月
适用年级:2023级
适用专业:智能医学工程
文档内容:
讲稿课件(教学版):智能医学工程-计算机程序设计-课件-第11章-多线程-教学版.pdf
讲稿课件(笔记版):智能医学工程-计算机程序设计-课件-第11章-多线程-笔记版.pdf
讲稿课件(在线版):
学习资源:
代码:eg11.1.1
// 创建一个继承自Thread类的子类
class MyThread extends Thread {
private String message;
// 构造方法,接收要打印的信息
public MyThread(String message) {
this.message = message;
}
// 覆盖Thread类的run方法
@Override
public void run() {
// 循环打印信息10次
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ": " + this.message + " " + i);
// 为了看到更明显的并发效果,这里让线程休眠一下
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MultiThreadingExample {
public static void main(String[] args) {
// 创建两个线程实例
MyThread thread1 = new MyThread("Hello from Thread 1");
MyThread thread2 = new MyThread("Hello from Thread 2");
// 启动线程
thread1.start();
thread2.start();
// 注意:start()方法调用后,线程会进入就绪状态,等待CPU的调度执行
// main线程也会继续向下执行,不会等待thread1和thread2执行完毕
}
}代码:eg11.1.1-2
/*
在Java中,与多线程(Threads)不同,多进程(Processes)的概念并不是Java直接支持的核心特性,因为Java是设计为一种运行在Java虚拟机(JVM)上的语言,它主要关注于线程级别的并发。然而,Java程序可以通过运行时环境(如操作系统)间接地创建和管理多个进程。
在Java中,通常使用Runtime.getRuntime().exec(String command)方法或ProcessBuilder类来启动外部进程。这里我将给出一个使用ProcessBuilder类来启动多个外部命令(可以视为多个进程)的简单示例。请注意,这些外部命令实际上是在操作系统的层面上作为独立的进程运行的。
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MultiProcessExample {
public static void main(String[] args) {
// 创建一个ProcessBuilder实例来启动notepad.exe(记事本)作为一个进程(示例,请根据实际情况调整)
ProcessBuilder processBuilder1 = new ProcessBuilder("notepad.exe");
try {
Process process1 = processBuilder1.start();
System.out.println("Process 1 started.");
// 注意:在实际应用中,你可能需要等待或处理process1的输出/错误流
// 另一个示例,使用cmd.exe来运行dir命令(在Windows上)
ProcessBuilder processBuilder2 = new ProcessBuilder("cmd.exe", "/c", "dir");
Process process2 = processBuilder2.start();
// 读取process2的输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process2.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Process 2 Output: " + line);
}
// 等待process2结束
int exitCode = process2.waitFor();
System.out.println("Process 2 exited with code " + exitCode);
// 注意:这里没有显式地结束process1,因为它是一个GUI应用程序(记事本)。
// 在实际应用中,你可能需要根据你的需求来管理这些进程的生命周期。
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}代码:eg11.1.2
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
System.out.println("State after creation: " + t1.getState()); // 新建状态
t1.start();
System.out.println("State after start: " + t1.getState()); // 就绪或运行状态
}
}代码:eg11.1.3
class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " is running with priority " + getPriority());
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
t3.start();
}
}代码:eg11.2.1
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // 启动线程
}
}代码:eg11.2.2
class MyThread extends Thread {
public void run() {
for(int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); // 启动第一个线程
t2.start(); // 启动第二个线程
}
}代码:eg11.2.3
class MyRunnable implements Runnable {
public void run() {
for(int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread t1 = new Thread(myRunnable);
Thread t2 = new Thread(myRunnable);
t1.start(); // 启动第一个线程
t2.start(); // 启动第二个线程
}
}代码:eg11.3.1
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for(int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for(int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final count: " + counter.getCount()); // 应为2000
}
}代码:eg11.3.2
class SharedResource {
private boolean available = false;
public synchronized void produce() {
while (available) {
try {
wait(); // 等待,直到资源被消费
} catch (InterruptedException e) {
e.printStackTrace();
}
}
available = true;
System.out.println("Produced resource");
notify(); // 通知等待的线程可以消费资源
}
public synchronized void consume() {
while (!available) {
try {
wait(); // 等待,直到资源被生产
} catch (InterruptedException e) {
e.printStackTrace();
}
}
available = false;
System.out.println("Consumed resource");
notify(); // 通知等待的线程可以生产资源
}
}
public class Main {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread producer = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.produce();
}
});
Thread consumer = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.consume();
}
});
producer.start();
consumer.start();
}
}代码:eg11.4
import java.util.Timer;
import java.util.TimerTask;
class ReminderTask extends TimerTask {
public void run() {
System.out.println("Task executed!");
}
}
public class Main {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new ReminderTask(), 5000); // 5秒后执行任务
System.out.println("Task scheduled. It will run after 5 seconds.");
}
}软件资源:

