继承Thread
public static class MyThread extends Thread
{
@Override
public void run()
{
System.out.println("i am a thread");
}
}
public static void main(String[] args)
{
MyThread myThread = new MyThread();
myThread.start();
}
实现Runnable
public static class RunnableTask implements Runnable
{
@Override
public void run()
{
System.out.println("i am a child thread");
}
}
public static void main(String[] args)
{
RunnableTask runnableTask = new RunnableTask();
new Thread(runnableTask).start();
new Thread(runnableTask).start();
}
FutureTask
public static class CallerTask implements Callable<String>
{
@Override
public String call() throws Exception
{
return "hellow";
}
}
public static void main(String[] args)
{
FutureTask<String> futureTask = new FutureTask<>(new CallerTask());
new Thread(futureTask).start();
String result = null;
try
{
result = futureTask.get();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(result);
}
输出:hellow
调用strat方法后程序并不是马上执行而是出于就绪状态,等待获取CPU的资源