java程序设计开发,Java高级API-多线程学习笔记
多线程基础概念
线程与进程
- 进程:是程序在操作系统中的一次执行过程,是系统进行资源分配和调度的基本单位。
- 线程:是进程中的一个执行单元,是 CPU 调度和分派的基本单位。一个进程可以包含多个线程。
多线程的优点
- 提高程序的响应速度:例如在图形界面程序中,一个线程负责处理用户的输入,另一个线程负责后台数据的加载和处理,这样可以避免界面的卡顿。
- 提高 CPU 的利用率:当一个线程在进行 I/O 操作时,CPU 可以调度其他线程执行,从而提高 CPU 的利用率。
- 便于进行模块化设计:可以将不同的功能模块分配给不同的线程执行,提高代码的可维护性和可扩展性。
创建线程的方式
继承Thread
类
class MyThread extends Thread {
@Override
public void run() {
System.out.println("MyThread is running");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
重点:start()
方法会启动一个新的线程,并调用run()
方法。不能直接调用run()
方法,否则只是在当前线程中执行run()
方法的代码,而不会启动新的线程。
实现Runnable
接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("MyRunnable is running");
}
}
public class RunnableExample {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
重点:实现Runnable
接口的类可以更好地实现资源共享,因为多个线程可以共享同一个Runnable
对象。
实现Callable
接口
import java.util.concurrent.*;
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return 1 + 2;
}
}
public class CallableExample {
pub