用java写一个线程工具类
时间: 2024-05-14 15:14:38 浏览: 10
以下是一个简单的线程工具类,可以用于线程的创建、暂停、继续和停止:
```
public class ThreadUtils {
private static class PauseableThread extends Thread {
private volatile boolean isPaused;
public synchronized void pauseThread() {
isPaused = true;
}
public synchronized void resumeThread() {
isPaused = false;
notify();
}
public void run() {
while (!isInterrupted()) {
try {
synchronized (this) {
while (isPaused) {
wait();
}
}
// 这里写线程执行的代码
} catch (InterruptedException e) {
interrupt();
}
}
}
}
public static Thread createThread(Runnable runnable) {
return new PauseableThread() {
public void run() {
super.run();
runnable.run();
}
};
}
public static void pauseThread(Thread thread) {
if (thread instanceof PauseableThread) {
((PauseableThread) thread).pauseThread();
}
}
public static void resumeThread(Thread thread) {
if (thread instanceof PauseableThread) {
((PauseableThread) thread).resumeThread();
}
}
public static void stopThread(Thread thread) {
if (thread != null) {
thread.interrupt();
}
}
}
```
使用示例:
```
Thread thread = ThreadUtils.createThread(new Runnable() {
public void run() {
// 这里写线程执行的代码
}
});
thread.start();
ThreadUtils.pauseThread(thread);
ThreadUtils.resumeThread(thread);
ThreadUtils.stopThread(thread);
```