首页 > 图灵资讯 > java面试题>正文

java多线程面试题-创建线程方式

2024-05-17 13:32:38

实现 Runnable 接口(优先使用)
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; }}
上一篇 java多线程面试题-wait和sleep区别
下一篇 java多线程面试题-线程池构造函数

文章素材均来源于网络,如有侵权,请联系管理员删除。