1. 继承Thread
1.1创建类并且继承Thread类,重写 run() 方法。
package cn.zzw;
public class FirstThread extends Thread
{
@Override
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(2000);
System.out.println("zzw,i="+i);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
1.2 调用start() 方法来启动线程。
public class ThreadDemo
{
public static void main(String[] args)
{
new FirstThread().start();
}
}
1.3 结果:
2. 实现Runnable接口创建线程类
2.1 定义runnable接口的实现类,并重写该接口的run()方法
package cn.zzw;
public class SecondRunnable implements Runnable
{
@Override
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(2000);
System.out.println("SecondRunnable: i="+i);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
2.2 调用线程对象的start()方法来启动该线程。
package cn.zzw;
public class ThreadDemo
{
public static void main(String[] args)
{
Runnable runnable = new SecondRunnable();
new Thread(runnable).start();
}
}
2.3 结果:
3. 通过Callable和Future创建线程
3.1 创建Callable接口的实现类,并实现call()方法,该方法有返回值
package cn.zzw;
import java.util.concurrent.Callable;
public class ThirdCallable implements Callable<Integer>
{
@Override
public Integer call() throws Exception
{
//TODO
return 100;
}
}
3.2 使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。
3.3 使用FutureTask对象作为Thread对象的target创建并启动新线程。
3.4 使用FutureTask对象的get()方法来获得子线程执行结束后的返回值。
package cn.zzw;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadDemo
{
public static void main(String[] args)
{
Callable callable=new ThirdCallable();
FutureTask<Integer> ft = new FutureTask<>(callable);
new Thread(ft).start();
try
{
Integer result = ft.get();
System.out.println("Result: result="+result);
} catch (InterruptedException e)
{
e.printStackTrace();
} catch (ExecutionException e)
{
e.printStackTrace();
}
}
}
3.5 结果:
4.三种方式的比较:
实现Runnable接口和实现Callabled接口的调用方式相同,实现Callable执行的call 方法有返回值。这两种方法还可以继承其他类。而采用继承Thread的方式,不能再继承其他父类,编写方法也比较简单。