线程实现的三种方法
1、范例 :继承Thread类:
Thread类是在java.lang包中定义的,继承Thread类必须重写run()方法
定义格式如下:
package cn.test;
class MyThread extends Thread{
private String str;
public MyThread(String str){
this.str = str;
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(this.str+"="+i);
}
}
}
public class Test {
public static void main(String[] args) {
new MyThread("线程一").start();
new MyThread("线程二").start();
new MyThread("线程三").start();
}
}
线程所有处理都在run()中进行定义,线程启动是调用start()方法,才是真正启动线程,而启动start()方法时会自动调用run()方法
2、范例: 实现runnable接口:
package cn.test;
class MyThread implements Runnable{
private String str;
public MyThread(String str){
this.str = str;
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(this.str+"i="+i);
}
}
}
public class Test {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread("线程一:"));
Thread t2 = new Thread(new MyThread("线程二:"));
Thread t3 = new Thread(new MyThread("线程三:"));
t1.start();
t2.start();
t3.start();
}
}
3、范例:实现Callable接口
package cn.test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyThread implements Callable<String>{
private String title;
public MyThread(String title){
this.title = title;
}
public String call()throws Exception{
for (int i = 0; i < 10; i++) {
System.out.println(title+"i="+i);
}
return "线程执行完毕";
}
}
public class Test {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<String> task1 = new FutureTask<>(new MyThread("线程一"));
FutureTask<String> task2 = new FutureTask<>(new MyThread("线程二"));
new Thread(task1).start();
new Thread(task2).start();
System.out.println("线程返回数据一"+ task1.get());
System.out.println("线程返回数据二"+ task2.get());
}
}