public class RunnableThread implements Runnable { @Override public void run() {System.out.println('用实现Runnable接口实现线程');}}
实现Callable接口(有返回值可抛出异常)
class CallableTask implements Callable<Integer> { @Override public Integer call() throws Exception { return new Random().nextInt();}}
继承Thread类(java不支持多继承)
public class ExtendsThread extends Thread { @Override public void run() {System.out.println('用Thread类实现线程');}}
使用线程池(底层都是实现run方法)
static class DefaultThreadFactory implements ThreadFactory { 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; }}
![](/images/780-200-2.jpg)