Java 多线程三种实现方式
Java多线程的实现方式:
1.继承Thread类,重写run()方法。
/** * @author suwan * @date 2019/6/14 */ public class ThreadTest extends Thread{ private String threadName; public ThreadTest(String name) { this.threadName = name; System.out.println("创建线程:"+name); } @Override public void run() { for (int i =0 ;i<10;i++){ System.out.println(threadName+" i="+i); } } }
/** * @author suwan * @date 2019/6/14 */ public class Test { public static void main(String[] args){ Thread thread = new ThreadTest("线程1"); Thread thread1 = new ThreadTest("线程2"); thread.start(); thread1.start(); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
输出: 创建线程:线程1 创建线程:线程2 线程1 i=0 线程1 i=1 线程1 i=2 线程1 i=3 线程1 i=4 线程1 i=5 线程1 i=6 线程1 i=7 线程1 i=8 线程2 i=0 线程1 i=9 线程2 i=1 线程2 i=2 线程2 i=3 线程2 i=4 线程2 i=5 线程2 i=6 线程2 i=7 线程2 i=8 线程2 i=9
2.实现runable接口:
/** * @author suwan * @date 2019/6/14 */ public class RunableTest implements Runnable { @Override public void run() { for (int i =0 ;i<10;i++){ System.out.println(Thread.currentThread().getName()+" i="+i); } } }
/** * @author suwan * @date 2019/6/14 */ public class Test { public static void main(String[] args){ RunableTest runableTest = new RunableTest(); Thread thread = new Thread(runableTest); Thread thread1 = new Thread(runableTest); thread.start(); thread1.start(); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
输出: Thread-1 i=0 Thread-1 i=1 Thread-0 i=0 Thread-0 i=1 Thread-0 i=2 Thread-1 i=2 Thread-1 i=3 Thread-1 i=4 Thread-0 i=3 Thread-1 i=5 Thread-0 i=4 Thread-1 i=6 Thread-1 i=7 Thread-1 i=8 Thread-0 i=5 Thread-1 i=9 Thread-0 i=6 Thread-0 i=7 Thread-0 i=8 Thread-0 i=9
3.通过Callable和FutureTask:
import java.util.concurrent.Callable; /** * @author suwan * @date 2019/6/14 */ public class CallableTest implements Callable<Integer> { @Override public Integer call() throws Exception { int i =0; for (;i<5;i++){ System.out.println(Thread.currentThread().getName()+" i="+i); } return i; } }
import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /** * @author suwan * @date 2019/6/14 */ public class Test { public static void main(String[] args){ CallableTest callableTest = new CallableTest(); FutureTask<Integer> futureTask = new FutureTask<>(callableTest); new Thread(futureTask,"线程:").start(); try { System.out.println("线程运算后结果:i= "+futureTask.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
输出: 线程: i=0 线程: i=1 线程: i=2 线程: i=3 线程: i=4 线程运算后结果:i= 5
涉及知识点:
1.线程对象调用start()方法之后,就说明线程进入就绪状态,等待JVM里的线程调度器的调度。
2.就绪状态下的线程如果获得了cpu资源,就可以执行run(),这时线程便处于运行状态。当线程执行sleep()之后便会进入睡眠,在睡眠结束后就会重新进入就绪状态。
三种方法的比较:
1.继承Thread:由于已经继承了Thread类,就不能再继承别的类了。
2.实现Runable:避免单继承,没有返回值。
3.实现Callable:避免单继承,有返回值。