您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Java中Thread的示例分析
## 1. 线程基础概念
在Java中,`Thread`类是用于创建和管理线程的核心类。每个线程代表一个独立的执行路径,允许程序实现并发执行。
### 1.1 线程生命周期
- **NEW**: 通过`new Thread()`创建但未启动
- **RUNNABLE**: 调用`start()`后进入可运行状态
- **BLOCKED**: 等待监视器锁(同步块)
- **WTING**: 无限期等待其他线程操作
- **TIMED_WTING**: 带超时的等待
- **TERMINATED**: 执行完成或异常终止
## 2. 创建线程的两种方式
### 2.1 继承Thread类
```java
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running: " + getName());
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // 启动线程
}
}
特点: - 简单直接 - 由于Java单继承限制,扩展性较差
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread running: " +
Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
Thread t2 = new Thread(new MyRunnable());
t2.start();
}
}
优势: - 避免单继承限制 - 更适合资源共享场景
Thread t = new Thread(() -> {
try {
Thread.sleep(1000); // 暂停1秒
System.out.println("After sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t.start();
t.join(); // 等待线程结束
System.out.println("Main thread continues");
Thread high = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("High priority");
}
});
high.setPriority(Thread.MAX_PRIORITY);
Thread low = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("Low priority");
}
});
low.setPriority(Thread.MIN_PRIORITY);
low.start();
high.start();
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public void add(int value) {
synchronized(this) {
this.count += value;
}
}
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class SafeCounter {
private final Lock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
class Message {
private String msg;
public synchronized void set(String msg) {
this.msg = msg;
notify(); // 唤醒等待线程
}
public synchronized String get() {
while (msg == null) {
try {
wait(); // 释放锁并等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String temp = msg;
msg = null;
return temp;
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolDemo {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("Task " + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {}
System.out.println("All tasks completed");
}
}
class WorkerThread implements Runnable {
private String task;
public WorkerThread(String task) {
this.task = task;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()
+ " processing " + task);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
CountDownLatch
, CyclicBarrier
等ConcurrentHashMap
等线程安全集合Java线程编程是并发处理的核心技术,正确理解Thread类的使用方法和线程同步机制,对于开发高性能、线程安全的应用程序至关重要。随着Java版本更新,更推荐使用java.util.concurrent
包中的高级API来处理并发问题。
“`
注:本文约1100字,涵盖了Java线程的基础使用、同步控制、线程通信和线程池等核心内容,采用Markdown格式编写,包含代码示例和结构化说明。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。