夯实Java基础,一篇文章全解析线程问题原创
1. 线程是什么
2. 怎样创建线程
- 继承Thread类
- 实现Runnable接口
- 实现Callable接口
- 使用线程池创建
2.1 继承Thread类
public class ThreadDemo {
public static void main(String[] args) {
Thread thread = new MyThread();
thread.start(); // 启动线程
}
}
class MyThread extends Thread {
@Override
public void run() {
System.out.println("关注公众号:一灯架构");
}
}
关注公众号:一灯架构
2.2 实现Runnable接口
public class ThreadDemo {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable, "线程1");
Thread thread2 = new Thread(myRunnable, "线程2");
thread1.start(); // 启动线程1
thread2.start(); // 启动线程2
}
}
class MyRunnable implements Runnable {
private int count = 5;
@Override
public void run() {
while (count > 0) {
System.out.println(Thread.currentThread().getName()
+ ",关注公众号:一灯架构," + count--);
}
}
}
线程2,关注公众号:一灯架构,4
线程1,关注公众号:一灯架构,5
线程1,关注公众号:一灯架构,2
线程1,关注公众号:一灯架构,1
线程2,关注公众号:一灯架构,3
2.3 实现Callable接口
public class ThreadTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable = new MyCallable();
FutureTask<String> futureTask = new FutureTask<String>(myCallable);
Thread thread = new Thread(futureTask);
thread.start();
System.out.println(futureTask.get());
}
}
class MyCallable implements Callable {
@Override
public String call() throws Exception {
return "关注公众号:一灯架构";
}
}
关注公众号:一灯架构
2.4 使用线程池创建
public class ThreadDemo {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(() -> System.out.println("关注公众号:一灯架构"));
}
}
关注公众号:一灯架构
3. 线程的状态
- NEW(初始化)
- RUNNABLE(可运行)
- WAITING(等待)
- TIMED_WAITING(超时等待)
- BLOCKED(阻塞)
- TERMINATED(终止)
4. 线程常用方法
方法定义 |
含义 |
使用方式 |
public synchronized void start() {……} |
启动线程 |
MyThread myThread = new MyThread(); myThread.start(); |
public static native Thread currentThread(); |
获取当前线程实例对象 |
Thread thread = Thread.currentThread(); |
public static native void yield(); |
让出CPU时间片 |
Thread.yield(); |
public static native void sleep(long millis); |
睡眠指定时间 |
Thread.sleep(1L); |
public void interrupt() {……} |
中断线程 |
MyThread myThread = new MyThread(); myThread.interrupt(); |
public static boolean interrupted() {……} |
判断线程是否已中断 |
MyThread myThread = new MyThread(); boolean interrupted = myThread.isInterrupted(); |
public final native boolean isAlive(); |
判断线程是否是存活状态 |
MyThread myThread = new MyThread(); boolean alive = myThread.isAlive(); |
public final String getName() {……} |
获取线程名称 |
MyThread myThread = new MyThread(); String name = myThread.getName(); |
public State getState() {……} |
获取线程状态 |
MyThread myThread = new MyThread(); Thread.State state = myThread.getState(); |
public long getId() {……} |
获取线程ID |
MyThread myThread = new MyThread(); long id = myThread.getId(); |
public final void join() {……} |
等待其他线程执行完再执行 |
MyThread myThread = new MyThread(); myThread.join(); |
我是「一灯架构」,如果本文对你有帮助,欢迎各位小伙伴点赞、评论和关注,感谢各位老铁,我们下期见