1、实现Runnable接口,重写run方法,并将该对象传入Thread对象的构造方法中。代码示例如下:
public class RunnableThread implements Runnable { @Override public void run() { System.out.println("RunnableThread run"); } public static void main(String[] args) { RunnableThread runnableThread = new RunnableThread(); Thread thread = new Thread(runnableThread); thread.start(); } }
2、继承Thread类,重写run方法。代码示例如下:
public class ExtendsThread extends Thread { @Override public void run() { System.out.println("ExtendsThread run"); } public static void main(String[] args) { ExtendsThread extendsThread = new ExtendsThread(); extendsThread.start(); } }
3、线程池中由线程工厂创建线程,本质上是new Thread()创建的。jdk源码如下:
/** * The default thread factory */ static class DefaultThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; DefaultThreadFactory() { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } }
4、实现Callbale<V>接口,重写call方法。代码示例如下:
public class CallableThread implements Callable<String> { @Override public String call() throws Exception { return "CallableThread call"; } public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<String> future = executorService.submit(new CallableThread()); String s = future.get(); System.out.println(s); } }
5、定时器Timer中有一个TimerThread,本质上还是通过继承Thread创建线程的。jdk源码如下:
public class Timer { /** * The timer thread. */ private final TimerThread thread = new TimerThread(queue); // 省略了一些代码 }
class TimerThread extends Thread { // 省略了一些代码 }
6、匿名内部类或lambda创建线程,代码示例如下:
public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()); } }).start(); }
public static void main(String[] args) { new Thread(() -> System.out.println(Thread.currentThread().getName())).start(); }