Java--JUC--实现线程的方式
- 线程的实现方式
- 继承Thread类
- 实现Runnable接口
- 实现Callable接口
- 线程池
- Thread方式:
-
package com.model.thread; //线程实现的第一种方法 public class Thread_001 extends Thread{ @Override public void run() { for (int i = 0; i <10 ; i++) { System.out.println("我在执行run方法"); } } public static void main(String[] args) { Thread_001 thread_001=new Thread_001(); thread_001.start(); //另外开启一个线程,实现两个线程同时执行 for (int i = 0; i < 20; i++) { System.out.println("我在执行主方法"); } } }
-
- Runnable接口方式
-
package com.model.thread; //创建线程的方式二 public class Thread_002 implements Runnable{ @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println("执行了子线程"); } } // 推荐使用Runnable接口实现类来实现线程的创建 public static void main(String[] args) { //先创建Runnable的接口实现类对象 Thread_002 thread_002=new Thread_002(); //再通过创建Thread类开启线程 new Thread(thread_002,"ONE").start(); for (int i = 0; i < 20; i++) { System.out.println("执行了主线程"); } //第二种方式使用Runnable实现线程,类不必实现接口,在实现线程的时候直接调用业务方法就可以了 Thead_003 thead_003=new Thead_003(); new Thread(() ->{ thead_003.get(); },"TWO").start(); //第三种实现方式 new Thread(new Runnable() { @Override public void run() { thead_003.get(); } },"TWO_01").start(); } } //Runnable实现的第二中调用 class Thead_003{ public void get(){ System.out.println("get two thread in Runnable"); } }
-
-
Callable实现方式
-
package com.model.concurrent; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; class Thread01 implements Runnable{ @Override public void run() { } } //第三种实现Callable方式实现线程 class Thread02 implements Callable<Integer>{ @Override public Integer call() throws Exception { return 1024; } } public class CallableDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { // FutureTask实现了Callable接口所以可以new FutureTask(new Thread02()) // FutureTask又是Runnable子类(RunnableFuture<V>)的实现类所以可以new Thread(FutureTask,"线程名") FutureTask futureTask=new FutureTask(new Thread02()); new Thread(futureTask,"A").start(); // Integer integer= (Integer) futureTask.get(); } }
-