- 实现方式:
- 通过继承Thread类实现一个线程
- 通过实现Runnable接口实现一个线程
继承的扩展性不强,Java总是支持单继承,如果一个类继承Thread就不能继承其他的类
- 怎么启动:
public class MainTest {
public static void main(String[] args) {
Thread thread = new Thread(new MyThread());
thread.start();
}
}
public class MyThread extends Thread{
@Override
public void run(){
System.out.println("被执行啦");
}
}
启动线程使用start方法,而启动了以后执行的是run方法
- 怎么区分线程?在一个系统中有很多线程,每个线程都会打印日志,我想区分是哪个线程打印的怎么办?
使用thread.setName(“设置一个线程名称”); 来设置一个线程名称。
这是一种规范,在创建线程完成后,都需要设置名称。