多线程之实现方式
- extends Thread
1.单继承 implements Ranable
1.多实现
2.多个Thread 可以共享一个多线程的资源(实现了Runable);public class duoxianchengtest1 implements Runnable {
int i = 10;
@Override
public void run() {
while (true){
if(i<1){
System.out.println(i);
break;
}else {
System.out.println(i);
i–;
}
}
}
}
public static void main(String[] args) {
duoxianchengtest1 duoxianchengte = new duoxianchengtest1();
Thread thread = new Thread(duoxianchengte);
Thread thread1= new Thread(duoxianchengte);
Thread thread2 = new Thread(duoxianchengte);
thread.start();
thread1.start();
thread2.start();
}}
结果:10
9
8
7
6
5
4
3
2
1
0
0
0
从结果可以看出,这个共享变量int是线程不安全的直接调用start()
1.新建线程进入可运行状态,新线程里会自动执行run方法,run方法运行在新的线程里- 直接调用run()
1.在当前线程里手动直接调用了run(),新建多线程类就相当于一个普通类,普通的方法调用