1.继承Thread类 重写run方法
public class TreadTest01 extends Thread{ @SneakyThrows @Override public void run() { for (int i = 0; i < 100; i++) { Thread.sleep(100); System.out.println(Thread.currentThread().getName()+"运行了"+i); } } public static void main(String[] args) { TreadTest01 treadTest01 = new TreadTest01(); treadTest01.setName("tread01"); treadTest01.run(); TreadTest01 treadTest02 = new TreadTest01(); treadTest02.run(); System.out.println("执行完成...."); } }
2.实现Runnable接口 重写run方法
public class RunnableTest { /** * 多线程第二种启动方式: * 1.自己定义一个类去实现 runnable接口 * 2.重新run方法--线程执行的代码 * 3.创建自己的对象 * 4.创建一个Thread类的对象 并开启线程 */ public static class MyRun implements Runnable{ @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName()+":hello thead"+i); } } } public static void main(String[] args) { // 任务 MyRun myRun = new MyRun(); // 线程1 Thread t1=new Thread(myRun); t1.start(); t1.setName("线程1"); // 线程2 Thread t2=new Thread(myRun); t2.start(); t2.setName("线程2"); } }
3.实现Callable 重写call方法 配合FuterTask获取线程结果
public class CallableTest { /** * 多线程第三种启动方式: * 解决:多线程其他两种没有返回值 * 特点:可以获取多线程的运行结果 * * 1.创建一个类 实现Callabel接口 * 2.重写 call(有返回值表示结果) * 3.创建任务对象 * 4.创建 FutureTask对象(管理多线程结果) * 5.创建Thread类并启动, */ public static class MyCallableTest implements Callable<Integer>{ @Override public Integer call() { int sum=0; for (int i = 0; i < 100; i++) { sum=sum+i; } return sum; } } public static void main(String[] args) throws ExecutionException, InterruptedException { MyCallableTest myCallableTest = new MyCallableTest(); FutureTask<Integer> futureTask = new FutureTask(myCallableTest); Thread thread = new Thread(futureTask); thread.start(); System.out.println(futureTask.get()); ExecutorService executorServiceCach = Executors.newCachedThreadPool(); } }
4.利用线程池启动线程
public class TestThreadPool { public static void main(String[] args) { ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 1000, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); threadPoolExecutor.execute(new Runnable() { @Override public void run() { System.out.println("aaaa"); } }); } }
本质:以下所有的启动方式本质上都是实现 runnable接口
标签:java,Thread,启动,void,run,线程,new,中线,public From: https://www.cnblogs.com/javacx/p/17444310.html