public class EvenNumberTest {
public static void main(String[] args) {
//3.创建Thread子类对象
PrintNumber p1=new PrintNumber();
//4.执行start()方法
p1.start();
//主线程输出带*的数字,对照看是否有交叠
for (int i = 0; i < 1000; i++) {
System.out.println(i+"*************");
}
}
}
//1.继承Thread类
class PrintNumber extends Thread{
//2.重写run()方法
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
if(i%2==0){
System.out.println(i);
}
}
}
}
问:是否可以使用run()代替start()方法?
不可以,这样会仍然执行main线程,run()被看作一个普通方法。
问:再提供一个分线程用于1000内偶数的遍历,再多一个start()操作?
不可以,第一个线程操作时线程状态会改变,再进入该线程会报错。
正确方法:再创建一个对象执行start()
public class EvenNumberTest {
public static void main(String[] args) {
//3.创建Thread子类对象
PrintNumber p1=new PrintNumber();
//4.创建Thread类的对象,将接口实现类的子对象作为参数传入
Thread t1=new Thread(p1);
//5.Thread类的对象,执行start()
t1.start();
}
}
//1.创建实现Runnable接口的类
class PrintNumber implements Runnable{
//2.实现run()方法
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
if(i%2==0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}
Thread继承 | Runnable实现 |
---|---|
start()方法启动 | start()方法启动 |
创建对象是Thread子类对象 | 创建对象是Thread子类对象 |
类的继承,只能单继承 | 接口的实现,可以接口多实现 |
更适合处理有共享数据的问题 | |
实现了代码与数据的分离 | |
Thread类也是实现了Runnable接口(代理模式) |
推荐阅读:
vue.js:634 [Vue warn]: Property or method "userName" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See:
状态码:415,发送HTTP请求返回415状态码的解决办法
SpringBoot 整合 webapp时 访问404的解决办法
Vue 打开页面时就加载方法,例如查询
SpringCloud怎么调用多个服务的信息
Spring整合Mybatis
Controller之间的跳转
SpringCloud 加入 thymleaf前端页面的方法
Spring AOP的实现原理
This may be the result of an unspecified view, due to default view name generation
Seek respect, not attention.