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(); }}
输出:创建线程:线程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(); }}
输出:Thread-1 i=0Thread-1 i=1Thread-0 i=0Thread-0 i=1Thread-0 i=2Thread-1 i=2Thread-1 i=3Thread-1 i=4Thread-0 i=3Thread-1 i=5Thread-0 i=4Thread-1 i=6Thread-1 i=7Thread-1 i=8Thread-0 i=5Thread-1 i=9Thread-0 i=6Thread-0 i=7Thread-0 i=8Thread-0 i=9
3.通过Callable和FutureTask:
import java.util.concurrent.Callable;/** * @author suwan * @date 2019/6/14 */public class CallableTest implements Callable{ @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(); FutureTaskfutureTask = new FutureTask<>(callableTest); new Thread(futureTask,"线程:").start(); try { System.out.println("线程运算后结果:i= "+futureTask.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }}
输出:线程: 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:避免单继承,有返回值。