Thread继承
package java1;
class MyThread extends Thread{//线程的主体类
private String title;
public MyThread(String title) {
this.title=title;
}
public void run() {
for(int i=0;i<10;i++) {
System.out.println(this.title+"运行"+i);
}
}
}
public class L1 {
public static void main(String[] args) {
new MyThread("线程A").start();
new MyThread("线程B").start();
new MyThread("线程C").start();
}
}
Runnable接口(没有返回值)
package java1;
class MyThread implements Runnable{//线程的主体类
private String title;
public MyThread(String title) {
this.title=title;
}
public void run() {
for(int i=0;i<10;i++) {
System.out.println(this.title+"运行"+i);
}
}
}
public class L1 {
public static void main(String[] args) {
Thread a=new Thread(new MyThread("线程A"));
Thread b=new Thread(new MyThread("线程B"));
Thread c=new Thread(new MyThread("线程C"));
a.start();
b.start();
c.start();
}
}
callable接口(有返回值)
package java1;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyThread implements Callable<String>{//线程的主体类
public String call() throws Exception{
for(int i=0;i<10;i++) {
System.out.println("线程执行"+i);
}
return "线程执行完毕";
}
}
public class L1 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<String> task =new FutureTask<>(new MyThread());
new Thread(task).start();
System.out.print("线程返回数据"+task.get());
}
}