🙈作者简介:练习时长两年半的Java up主
🙉个人主页:程序员老茶
🙊 ps:点赞👍是免费的,却可以让写博客的作者开兴好久好久😎
📚系列专栏:Java全栈,计算机系列(火速更新中)
💭 格言:种一棵树最好的时间是十年前,其次是现在
🏡动动小手,点个关注不迷路,感谢宝子们一键三连
目录
课程名:Java
内容/作用:知识点/设计/实验/作业/练习
学习:Java Thread类详解
Java Thread类详解
Java中的Thread类是一个核心类,它提供了多线程编程的基本功能。本文将详细解释Thread类及其常用方法,并通过代码示例进行演示。
1. Thread类简介
Thread类是Java中实现多线程的基类,它继承自Object类。每个线程都有一个对应的Thread对象,通过调用该对象的start()方法来启动线程,调用stop()方法来停止线程。
2. 创建线程的方法
2.1 继承Thread类
要创建一个线程,可以通过继承Thread类并重写其run()方法来实现。然后创建该子类的实例,并调用其start()方法启动线程。
class MyThread extends Thread {
@Override
public void run() {
// 线程执行的任务
System.out.println("MyThread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // 启动线程
}
}
2.2 实现Runnable接口
另一种创建线程的方式是通过实现Runnable接口并重写其run()方法。然后将实现了Runnable接口的类的实例作为参数传递给Thread类的构造函数,最后调用Thread对象的start()方法启动线程。
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的任务
System.out.println("MyRunnable is running");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // 启动线程
}
}
3. 线程的生命周期
线程的生命周期包括以下五种状态:
- 新建(New):线程对象被创建后,还没有调用start()方法。
- 就绪(Runnable):线程对象调用了start()方法,但是还没有获得CPU时间片。
- 运行(Running):线程获得了CPU时间片,正在执行run()方法。
- 阻塞(Blocked):线程在等待锁的释放或者调用了sleep()、wait()等方法。
- 死亡(Terminated):线程执行完了run()方法或者因为异常而终止。
可以通过Thread类的getState()方法获取线程的状态。
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
System.out.println("Thread state: " + myThread.getState()); // 输出:Thread state: NEW
myThread.start();
System.out.println("Thread state: " + myThread.getState()); // 输出:Thread state: RUNNABLE
}
}
4. 线程同步与通信
线程同步与通信是多线程编程中的重要概念。Java提供了多种方式来实现线程之间的同步与通信,如synchronized关键字、ReentrantLock、Semaphore、CountDownLatch等。
4.1 synchronized关键字
synchronized关键字可以用于修饰方法或者代码块,确保同一时刻只有一个线程能够访问被修饰的资源。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized void decrement() {
count--;
}
public synchronized int getCount() {
return count;
}
}
4.2 ReentrantLock
ReentrantLock是一个可重入的互斥锁,相比于synchronized关键字,它提供了更多的灵活性。
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private int count = 0;
private ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public void decrement() {
lock.lock();
try {
count--;
} finally {
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
4.3 Semaphore
Semaphore是一个计数信号量,可以用来控制同时访问特定资源的线程数量。
import java.util.concurrent.Semaphore;
class Counter {
private int count = 0;
private Semaphore semaphore = new Semaphore(1);
public void increment() throws InterruptedException {
semaphore.acquire();
try {
count++;
} finally {
semaphore.release();
}
}
public void decrement() throws InterruptedException {
semaphore.acquire();
try {
count--;
} finally {
semaphore.release();
}
}
public int getCount() {
return count;
}
}
4.4 CountDownLatch
CountDownLatch是一个同步工具类,允许一个或多个线程等待其他线程完成操作。
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException {
int numThreads = 3;
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
new Thread(new Worker(latch)).start();
}
latch.await(); // 主线程等待其他线程完成任务
System.out.println("All threads finished");
}
}
class Worker implements Runnable {
private CountDownLatch latch;
public Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " is working");
Thread.sleep((long) (Math.random() * 1000)); // 模拟耗时操作
System.out.println(Thread.currentThread().getName() + " finished");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown(); // 完成任务后,计数器减一
}
}
}
5. 总结
本文详细介绍了Java中Thread类的用法和常见方法,包括创建线程、线程的生命周期、线程同步与通信等。希望对您学习Java多线程编程有所帮助。
往期专栏 |
---|
Java全栈开发 |
数据结构与算法 |
计算机组成原理 |
操作系统 |
数据库系统 |
物联网控制原理与技术 |