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());
}
}