JAVA创建线程的两种方法
JAVA 创建线程两种常见方式
implements Runnable:
-
实现线程类的创建: public class MyThread implements Runnable{ ... public void run(){ //定义线程执行任务 }.. }
-
调用类+调用线程: MyThread mThread = new Mythread(传参); Thread t1= new Thread(mThread);
-
线程开始执行:t1.start(); (这边也就是执行run中的内容)
运用runnable 接口创建线程类,public void run(){//打印初始化信息}
public class MyRunnable implements Runnable{
String message;
public MyRunnable(String text){
message=text;
}
public void run(){
System.out.println(message);
}
}
创建实例和线程
public class RUN{
public static void main(String[]args){
MyRunnable myRunnable=new MyRunnable("threadThread");
Thread t1=new Thread(myRunnable);
t1.start();
}
}
extends Thread:
-
创建继承线程类:public class MyThread extends{ ....public void run(){ //定义线程执行任务 }...}
-
调用类:MyThread t1= new MyThread();
-
执行线程任务:t1.start();
继承Thread类 extends
public class MyThread extends Thread{
String message;
public MyThread(String text){
message=text;
}
public void run(){
System.out.println(message);
}
}
创建实例和线程
public class Test{
public static void main(String args[]){
MyThread t1=new MyThread("threadTHREAD");
t1.start();
}
}

浙公网安备 33010602011771号