一. 线程:
进程(Process):是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础
线程(thread):进程中执行运算的最小单位,可完成一个独立的顺序控制流程
进程和线程的关系:一个线程只能属于一个进程,而一个进程可以有多个线程,但至少有一个线程
多线程:如果在一个进程中同时运行了多个线程,用来完成不同的工作,则称之为“多线程”,所谓的多线程是多个线程交替占 用CPU资源,而非真正的并行执行
主线程:main()所在的线程称为主线程。主线程是产生其他子线程的线程。主线程必须最后完成执行,因为它需要执行各种关闭操作
1. 创建线程 需要继承的类 Thread
2. 线程实现方式:
1)继承 Thread 类 : 通过继承 Thread 类并重写 run() 方法来定义线程的行为。
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " - " + i);
try {
Thread.sleep(1000); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start(); // 启动线程1
thread2.start(); // 启动线程2
}
}
2)实现 Runnable 接口: 通过实现 Runnable 接口并重写 run() 方法来定义线程的行为。这种方式更灵活,因为你可以将 Runnable 实例传递给 Thread 类的构造函数。
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " - " + i);
try {
Thread.sleep(1000); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(new MyRunnable());
thread1.start(); // 启动线程1
thread2.start(); // 启动线程2
}
}
二. 线程池 (ExecutorService)
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class MyTask implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " - " + i);
try {
Thread.sleep(1000); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ExecutorServiceExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(new MyTask());
executor.submit(new MyTask());
executor.shutdown(); // 关闭线程池
}
}
三.线程生命周期
线程的状态
线程在其生命周期中有多种状态:
新建(New): 线程被创建但尚未启动。
就绪(Runnable): 线程已经准备好运行,等待 CPU 分配时间片。
运行(Running): 线程正在执行。
阻塞(Blocked): 线程被阻塞,等待某个条件(如 I/O 操作完成或获取锁)。
等待(Waiting): 线程进入等待状态,直到其他线程唤醒它(如 wait() 方法)。
定时等待(Timed Waiting): 线程进入定时等待状态,等待指定的时间(如 sleep() 或 join() 方法)。
终止(Terminated): 线程执行完毕或因异常而终止。
四. 线程同步与互斥
当多个线程访问共享资源时,可能会导致数据不一致的问题。为了确保线程安全,Java 提供了多种同步机制:
synchronized 关键字: 用于方法或代码块,确保同一时刻只有一个线程可以执行该部分代码。
Lock 接口: 提供更灵活的锁定机制,如 ReentrantLock。
volatile 关键字: 确保变量的可见性,即一个线程对变量的修改会立即对其他线程可见。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class SynchronizationExample {
public static void main(String[] args) throws InterruptedException {
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();
t1.join();
t2.join();
System.out.println("Final count: " + counter.getCount()); // 输出 2000
}
}
五.线程通信
线程之间可以通过以下方式进行通信:
wait() / notify() / notifyAll(): 用于线程间的协作,通常与 synchronized 一起使用。
join(): 等待另一个线程完成。
yield(): 让出当前线程的执行权,让其他线程有机会执行。
class SharedResource {
private boolean ready = false;
public synchronized void produce() {
if (ready) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Produced");
ready = true;
notify();
}
public synchronized void consume() {
if (!ready) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Consumed");
ready = false;
notify();
}
}
public class ThreadCommunicationExample {
public static void main(String[] args) {
final 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();
}
}
六. Socket:
Socket又被称为套接字,包含IP地址+端口号。两个程序通信使用的
IP地址就是为了网络中区分多台计算机的。它可以代表计算机的唯一地址。
IP地址也是全球唯一的。类似于家里的门牌号。它的规范就是由4部分组成,每一部分范围都是0~255之间的数字。
端口号其实是一个数字,50000以后的端口基本都可以用,以前的大多属于计算机内部使用的。0~65536。区分应用