在我们平常的开发工作中,我们经常会用到线程,那么,线程相关的知识点在面试中也会经常问到。那么,今天来总结一下线程的主要知识点。
1:实现线程的方式有哪些?
继承Thread类和实现Runnable接口。因为java是单继承,多实现,所以推荐使用实现Runnable接口。
1)继承Thread类:
public class ThreadDemo1 extends Thread{
private String name;
public ThreadDemo1(String name){
this.name = name;
}
public void run(){
for(int i=0;i<200;i++){
System.out.println("售票员:"+this.name+"正在售票");
}
}
public static void main(String[] args){
ThreadDemo1 thread1 = new ThreadDemo1("小明");
ThreadDemo1 thread2 = new ThreadDemo1("小花");
thread1.start();
thread2.start();
}
}
2)实现Runnable接口:
public class ThreadDemo1 implements Runnable{
private String name;
public ThreadDemo1(String name){
this.name = name;
}
public void run(){
for(int i=0;i<200;i++){
System.out.println("售票员"+this.name+"正在售票");
}
}
public static void main(String[] args){
ThreadDemo1 thread1 = new ThreadDemo1("小明");
ThreadDemo1 thread2 = new ThreadDemo1("小花");
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
hread t3 = new Thread(thread3);
Thread t4 = new Thread(thread4);
Thread t5 = new Thread(thread5);
t1.start();
t2.start();
}
}
2:线程有几种状态?
线程有五种状态,分别是创建、就绪、运行、阻塞和死亡。
3:怎样启动一个线程?
调用start方法。当调用start方法后,线程处于就绪状态,当cpu分配时间片后,线程处于运行状态。只有调用了start方法,才会体现出多线程的特性。
4:start方法和run方法有什么区别?
重写run方法,在run方法中实现业务逻辑代码。如果只是调用run方法,那么是同步执行的,只有当前线程执行完,另一个线程才会执行。调用了start方法,run方法代码块可以交替执行,体现了多线程的特性。
5:如何让一个线程暂停一段时间?
调用sleep方法,参数中可以写具体的时间。如果唤醒当前休眠的线程,得到cpu的分配的时间片后,又可重新执行。也可以调用wait方法,使线程暂停一段时间。
6:如何停止一个线程?
调用stop方法,但是这个方法会强行停止正在进行的操作,这个方法是不安全的,现在已经被废弃,所以不建议使用stop方法。使用interrupt中断线程。
总结:以上总结了线程的基本知识点。
知识就是要不断的学习, 不断的复习,才会记忆的更加的深刻。加油,美好的风景一直在路上!