先看代码:继承Thread创建了一个线程,重写了run方法;
class Mythread extends Thread{
@Override
public void run() {
while(true){
System.out.println("Hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
再看代码:在main方法,也就是main主线程中new了Mythread的对象,并调用start();
public class demo1 {
public static void main(String[] args) {
Thread thread=new Mythread();
thread.start();
}
}
执行结果:
run方法是描述这个线程是要干什么,比如我的这个线程就是让它每间隔一秒就打印一次”Hello thread“;而start()就是让这个实例化的线程跑起来,两个从中文意思上看好像都是让线程执行起来,但是这个方法是完全不同的;
举个例子更好理解:run方法就是放学了之后你把作业是什么写下来在本子上,而start()方法就是开始写作业;