线程的状态
(1)新建:使用new关键字和Thread类或其子类建立一个线程对象后就是新建状态
(2)就绪:线程对象调用start()方法后
(3)运行:就绪状态获取CPU资源,就可以执行run()
(4)阻塞:线程执行sleep()、suspend()等方法,失去占用资源,进入阻塞状态,其分为:
- 等待阻塞:运行线程执行wait()方法
- 同步阻塞:线程在获取synchronized同步锁失败
- 其他阻塞:调用sleep()或join()发出了I/O请求时,也会阻塞
(5)死亡:线程完成任务或者其他终止条件发生时
线程的生命周期
新建状态,执行start()方法,就绪状态,执行run()方法获得CPU资源,运行状态,run()方法执行完毕,死亡,运行状态让出CPU()资源,阻塞状态。
创建线程的方法
(1)通过继承Thread类本身
(2)通过实现Runnable接口
(3)通过Callable和Future创建线程
class RunableTest1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
class RunnableTest2 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
class RunableTest3 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
sum += i;
}
return sum;
}
}
执行类
public class Frist {
public static void main(String[] args) {
RunableTest1 t1 = new RunableTest1();
t1.setName("继承Thread");
t1.start();
RunnableTest2 runnableTest2 = new RunnableTest2();
Thread t2 = new Thread(runnableTest2,"实现Runnable接口");
t2.start();
RunableTest3 runableTest3 = new RunableTest3();
FutureTask<Integer> futureTask = new FutureTask<>(runableTest3);
Thread t3 = new Thread(futureTask,"实现Callable");
t3.start();
try {
Integer integer = futureTask.get();
System.out.println("返回值(sum):" + integer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
网友评论