一、继承Thread,重写run方法
public class ThreadOne extends Thread { @Override public void run(){ System.out.println(System.currentTimeMillis()); } public static void main(String[] args) { Thread thread = new ThreadOne(); thread.start(); } }
二、实现Runnable,重写run方法
public class ThreadTwo implements Runnable { @Override public void run() { System.out.println(System.currentTimeMillis()); } public static void main(String[] args) { Thread thread = new Thread(new ThreadTwo()); thread.start(); } }
三、 实现Callable接口,重写call()方法,然后包装成java.util.concurrent.FutureTask, 再然后包装成Thread;可以获得返回值
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class ThreadThree implements Callable { @Override public Object call() throws Exception { return System.currentTimeMillis(); } public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask> task = new FutureTask<>(new ThreadThree()); new Thread(task).start(); System.out.println(task.get()); //获得返回值 } }
四、线程池创建线程
public class ThreadFour{ private final static Integer CORE_NUM = Runtime.getRuntime().availableProcessors(); private static AtomicInteger atomicInteger = new AtomicInteger(0); // 为何要定制ThreadFactory? // 1、为了能够设置一个更有意义的线程名 . // 2、自主选择线程类型:守护线程或用户线程 // 3、设置线程优先级 // 4、处理未捕捉的异常 private static ThreadFactory threadFactory = r -> new Thread(r, "thread-pool-"+ atomicInteger); private final static ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor( CORE_NUM,//核心线程池大小 CORE_NUM,//最大的线程池大小 3L,//超时了没有人调用就会释放 TimeUnit.MILLISECONDS,//超时单位 new linkedBlockingQueue(100),//阻塞队列 threadFactory, //创建一个新线程时使用的工厂,可以用来设定线程名、是否为daemon线程等等 new ThreadPoolExecutor.AbortPolicy() // 总是抛出拒绝执行异常 ); public static void main(String[] args) { POOL_EXECUTOR.execute(()-> System.out.println(System.currentTimeMillis())); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)