创建线程的三种方式
1、直接继承Thread
package newthrow; class MyThread extends Thread { MyThread(String name) { super(name); } public void run() { int i = 0; while(i < 20) { System.out.println(Thread.currentThread() + " i = " + i); i++; } } } public class Demo1 { public static void main(String[] args) throws Exception { MyThread t1 = new MyThread("t1"); t1.start(); Thread.sleep(1); System.out.println(Thread.currentThread()); } }
线程的调度机制是非确定性的。
几次运行的结果不一样,结果不可预料,可以自己试一下。
2、实现Runnable接口
class MyThread implements Runnable { public void run() { int i = 0; while(i < 20) { System.out.println(Thread.currentThread() + " i = " + i); i++; } } } public class Demo1 { public static void main(String[] args) throws Exception { Thread t1 = new Thread(new MyThread(),"t1"); t1.start(); Thread.sleep(1); System.out.println(Thread.currentThread()); } }
Runnable接口定义任务,线程驱动任务。
3、实现Callable接口
class Mycallable implements Callable<Integer> { public Integer call() { return 1+1; } } public class Demo6 { public static void main(String[] args) throws Exception { ExecutorService es = Executors.newSingleThreadExecutor(); Future<Integer> f = es.submit(new Mycallable()); System.out.println(f.get()); es.shutdown(); } }