刷面经看到有问这两个题目,整理来康康

一、线程的状态(6种状态)

新建(new)创建后尚未启动

可运行(runnable)可能正在运行也可能正在等时间片分配

阻塞(blocking)等待获取一个排他锁,如果其他线程释放了锁,就会结束阻塞状态

无限期等待(waiting)等待其他线程显示唤醒,一定时间后被系统自动唤醒

限期等待(timeed waiting)无需等待其他线程显式唤醒,一定时间后被系统自动唤醒

死亡(terminated)线程结束任务后自己结束或者遇到异常自己退出

二、创建线程的方式(3种)

1、继承runnable接口。重写run()方法

public class MyRunnable implements Runnable {
@Override
public void run() {
//方法体
}
}

public class MultiThread_1 {
public static void main(String[] args) {
MyRunnable mr=new MyRunnable();
Thread thread=new Thread(mr);
thread.start();
}
}

2.实现Callable接口,重写call()方法,与runnable接口不同callable可以有返回值

public class MyCallable implements Callable {
@Override
public Integer call() throws Exception {
return 123;
}
}

public class MultiThread_2 {
public static void main(String[] args) throws Exception {
MyCallable instance = new MyCallable();
FutureTask ft=new FutureTask<>(instance);
Thread thread = new Thread(ft);
thread.start();
System.out.println(ft.get());
}
}

3.继承thread类,同样需要重写run()方法,因为thread也实现了runnable接口

public class MyThread extends Thread{
public void run(){
\方法体
}
}

public static void main(String [] args){
MyThread mt=new MyThread();
mt.start();
}

posted @ 2020-09-03 15:03  静是本能  阅读(105)  评论(0编辑  收藏  举报