java 三种多线程的创建方法Thread,Handler,Runnable

时间:2022-09-20 17:31:55

 第一种方法:使用Thread 类的继承

public class myThread extends Thread {
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println(i);
}
}
}

调用:

myThread mmyThread = new myThread(); 
mmyThread.start();

myThread mmyThread2 = new myThread();
mmyThread2.run();


 第二种方法:使用Handler

new Handler().postDelayed(new Runnable() {

@Override
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println(i);
}
System.out.println("ok");
}
}, 1000);


第三种方法:使用 Runnable接口

public class ThreadRunnable implements Runnable {

@Override
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println(i);
}
}
}


调用:

ThreadRunnable sub = new ThreadRunnable(); 
Thread tsub= new Thread(sub);

tsub.start();