一:继承Thread类,重写run方法
package CreateThread;
public class ExtendThread {
public static void main(String[] args) {
MyThreadOne threadOne=new MyThreadOne();
threadOne.start();
for (int i = 0; i < 100; i++) {
System.out.println("main:" + i);
}
}
}
class MyThreadOne extends Thread{
@Override
public void run() {
for (int i = 0; i <10000 ; i++) {
System.out.println("myjob"+i);
}
}
}
这个方法不推荐,因为Java类是单继承的,这样会影响后续代码的扩展。
二:实现Runnable接口 重写run方法
package CreateThread;
public class ImplRunnable {
public static void main(String[] args) {
MyRunnable runnable =new MyRunnable();
Thread thread=new Thread(runnable);
thread.start();
for (int i = 0; i < 1000; i++) {
System.out.println("main:" + i);
}
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("MyRunnable:" + i);
}
}
}
最常用的方式如下:
匿名内部类:
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("匿名内部类:" + i);
}
}
}
);
thread.start();
for (int i = 0; i < 1000; i++) {
System.out.println("main:" + i);
}
lambda方式:
Thread t2 = new Thread(() -> {
for (int i = 0; i < 100; i++) {
System.out.println("lambda:" + i);
}
});
三:实现Callable 重写call方法,配合FutureTask
Callable一般用于有返回结果的非阻塞的执行方法
package CreateThread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class ImlCallable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable=new MyCallable();
// 创建FutureTask
FutureTask futureTask=new FutureTask(myCallable);
Thread thread=new Thread(futureTask);
thread.start();
//5. 做一些操作
//6. 要结果
Object count = futureTask.get();
System.out.println("总和为:" + count);
}
}
class MyCallable implements Callable {
@Override
public Object call() throws Exception {
int count = 0 ;
for (int i = 0; i < 100; i++) {
count = count+i;
}
return count ;
}
}