本文介绍java中两种线程创建的方法,第一种是通过继承Thread类然后调用其start方法,第二种是实现Runnable接口然后代理调用。
下面是第一种创建方法
package ThreadExercise;
/**
* version 2.0
*/
public class therad {
public static void main(String[] args) {
Cat cat = new Cat();
cat.start();
//在底层JVM调用start0方法,start0会调用run方法,所以start才是线程的开始,并不是run
try {
for (int i = 0; i < 4; i++) {
System.out.println(i);
Thread.sleep(1000);//会抛出异常所以进行了异常捕获
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
class Cat extends Thread{
int time = 0;
public void run(){
try {
while (true){
Thread.sleep(1000);
System.out.println(++time+Thread.currentThread().getName());//获取当前线程
的名字
if(time == 60 ){
break;
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);//会抛出异常所以进行了异常捕获
}
}
}
当我们的程序开始运行时会成为一个进程,执行到main方法是会创建一个名为main的线程,执行到start时又会创建一个子线程。需要注意的是当主线程结束时,子线程不会立即结束,而是会继续执行,直到结束。
这是第二种创建方法
package ThreadExercise;
/**
* @author庞慧斌最牛逼~~ version 2.0
*/
public class runable {
public static void main(String[] args) {
Dod dod = new Dod();//实现了Runnable接口的对象实例
Thread thread = new Thread(dod);//将dod对象作为参数传入Thread类
thread.start();
}
}
class Dod implements Runnable{
@Override
public void run() {
int i = 0;
while (true){
System.out.println(++i+Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (i==5){
break;
}
}
}
}
//这部分是模拟Thread类,以便于理解通过接口创建线程
class ThreadCopy{
private Runnable thread = null;
public ThreadCopy(Runnable thread) {
this.thread = thread;
}
public void Start(){
Start0();
}
public void Start0(){
run();
}
public void run(){
if(thread!=null){
thread.run();
}
}
}
以上就是两种创建方式,个人感觉使用上没有什么本质的区别,唯一的就是用Rannable的话可以将同一个对象作为参数传入不同的线程,做到资源共享。