三种方式
1. 继承Thread类创建线程类,通过start方法开启新线程
使用方式:
- 继承Thread类,并重写该类的run方法。
- new一个实例,通过start方法启动新线程
示例
package com.thread;
public class FirstThreadTest extends Thread{
int i = 0;
//重写run方法,run方法的方法体就是现场执行体
public void run()
{
for(;i<100;i++){
System.out.println(getName()+" "+i);
}
}
public static void main(String[] args)
{
for(int i = 0;i< 100;i++)
{
System.out.println(Thread.currentThread().getName()+" : "+i);
if(i==20)
{
new FirstThreadTest().start();
new FirstThreadTest().start();
}
}
}
}
复制代码
扩展
start和run方法的区别: start方法开启了一个新的线程,使线程处于就绪状态;run方法只是在当前线程执行实例方法,直接调用run方法并没有开启新的线程。
2. 实现Runnable接口
使用方式:
- 实现Runnable接口,并重写该类的run方法。
- new一个实例,将该实例作为Thread的target创建Thread对象
- 调用Thread的start方法
示例
package com.thread;
public class RunnableThreadTest implements Runnable
{
private int i;
public void run()
{
for(i = 0;i <100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
public static void main(String[] args)
{
for(int i = 0;i < 100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
if(i==20)
{
RunnableThreadTest rtt = new RunnableThreadTest();
new Thread(rtt,"新线程1").start();
new Thread(rtt,"新线程2").start();
}
}
}
}
复制代码
3. 实现Callable接口
使用方式
- 创建Callable接口的实现类,并实现call方法
- 创建Callable实现类的实例,并用FutureTask类来包装该实例
- 使用FutureTask实例作为target创建Thread实例
- 调用Thread实例的start方法
示例
package com.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableThreadTest implements Callable<Integer>
{
public static void main(String[] args)
{
CallableThreadTest ctt = new CallableThreadTest();
FutureTask<Integer> ft = new FutureTask<>(ctt);
for(int i = 0;i < 100;i++)
{
System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);
if(i==20)
{
new Thread(ft,"有返回值的线程").start();
}
}
try
{
System.out.println("子线程的返回值:"+ft.get());
} catch (InterruptedException e)
{
e.printStackTrace();
} catch (ExecutionException e)
{
e.printStackTrace();
}
}
@Override
public Integer call() throws Exception
{
int i = 0;
for(;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
return i;
}
}
复制代码
对比
Runnable/Callable和Thread对比
优势
- 通过实现接口,还可以继承其他类
- 多个线程可以共享同一个target,适合资源共享
劣势
- 编程稍微复杂,如果要访问当前线程,则必须使用Thread.currentThread()方法
Runnable和Callable的区别
- Callable可以有返回值,Runnable没有返回值
- Callable接口的call()方法允许抛出异常;而Runnable接口的run()方法的异常只能在内部消化,不能继续上抛
扩展:
Callable接口支持返回执行结果,此时需要调用FutureTask.get()方法实现,此方法会阻塞主线程直到获取‘将来’结果;当不调用此方法时,主线程不会阻塞
复制代码