线程的创建
线程的创建主要要3种方法。
1. 继承Thread类
package cn.zengzehao.thread;
public class FirstThread {
public static void main(String[] args) throws InterruptedException {
//创建线程
MyTaskThread thread = new MyTaskThread();
//或者这样子创建线程
//Thread thread = new Thread(new MyTaskThread());
//启动线程
thread.start();
}
}
class MyTaskThread extends Thread{
@Override
//重写父类的run()方法
public void run() {
System.out.println("我是继承Thread的线程");
}
}
- 实现Runnable接口
package cn.zengzehao.thread;
public class RunnableTest {
public static void main(String[] args) {
//创建线程
Thread thread = new Thread(new MyThread());
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("我是线程2");
}
});
//启动线程
thread.start();
thread2.start();
}
}
class MyThread implements Runnable{
//实现Runnable接口的run()方法
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println("我是实现Runnable");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- 通过Callable和Future创建线程
package cn.zengzehao.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableTest {
public static void main(String[] args) {
//使用FutureTask类来包装Callable对象
FutureTask<Integer> ft = new FutureTask<Integer>(new MyTask());
//启动线程
new Thread(ft).start();
try {
//获取线程返回的值
Integer sum = ft.get();
System.out.println("打印返回来的值:"+sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class MyTask implements Callable<Integer>{
//实现Callable的call()方法
@Override
public Integer call() throws Exception {
System.out.println("实现Callable");
int sum = 0;
for(int i=0;i<=100;i++){
sum+=i;
}
return sum;
}
}