线程(Thread)
- 线程(thread)是操作系统能够进行运算调度的最小单位。
Java创建线程三种方式
- 继承Thread
- 实现接口Runnable
- 实现Callable接口,重写call(),利用FutureTask包装Callable,并作为task传入Thread构造函数;
方式一:
- 继承Thread,重写run()。
- 实例化MyThreadOne,通过调用MyThreadOne的start()方法启动线程。
public class MyThreadOne extends Thread{
public void run(){
System.out.println("继承Thread类实现线程!");
}
public static void main(String[] args) {
MyThreadOne thread1 = new MyThreadOne();
MyThreadOne thread2 = new MyThreadOne();
MyThreadOne thread3 = new MyThreadOne();
thread1.start();
thread2.start();
thread3.start();
}
}
方式二:
- 实现Runnable接口,重写run()。
- 如果自己的类已经继承了别的类,那就只能实现Runnable接口了。
- 实例化Thread,再传入MyThreadOne的实例,通过调用Thread的start()方法。
public class MyThreadTwo implements Runnable{
@Override
public void run() {
System.out.println("实现接口Runable实现线程");
}
public static void main(String[] args) {
MyThreadOne thread1 = new MyThreadOne();
for (int i = 0; i<10; i++){
new Thread(thread1).start();
}
}
}
方式三:
- 实现Callable接口,重写call(),利用FutureTask包装Callable,并作为task传入Thread构造函数。
- 定义MyThreadThree实现Callable接口;
- 重写call();
- 创建FutureTask的对象;FutureTask中定义了run(),run()内部调用了call(),并保存了call()的返回值;
- 创建Thread的对象,传入参数Runnable接口;
- 启动线程,thread.start();
- 可通过FutureTask类的get()方法获得线程执行结束后的返回值,即call的返回值;
public class MyThreadThree implements Callable<Integer> {
int i = 0;
@Override
public Integer call() throws Exception {
System.out.println("执行call方法前i为:"+i);
i++;
return i;
}
public static void main(String[] args) throws Exception {
FutureTask<Integer> task = new FutureTask<Integer>(new MyThreadThree());
new Thread(task).start();
try {
System.out.println("执行call方法返回值i为:"+task.get());
}catch (Exception e){
e.printStackTrace();
}
}
}