线程问题,或称并发
创建线程一般有一下方法
- 继承Thread类,重写run方法
1 public class TestThread extends Thread{ 2 public void run() { 3 System.out.println("Hello World"); 4 } 5 public static void main(String[] args) { 6 Thread mThread = new TestThread(); 7 mThread.start(); 8 } 9 }
- 实现Runnable接口,并实现run方法
1 public class TestRunnable implements Runnable { 2 public void run() { 3 System.out.println("Hello World"); 4 } 5 } 6 7 public class TestRunnable { 8 public static void main(String[] args) { 9 TestRunnable mTestRunnable = new TestRunnable(); 10 Thread mThread = new Thread(mTestRunnable); 11 mThread.start(); 12 } 13 }
注意:Runnable 不是线程而是进程,或者称为thread的一个target
- 实现Callable接口,重写call()方法
public class TestCallable { public static class MyTestCallable implements Callable { public String call() throws Exception { retun "Hello World"; } } public static void main(String[] args) { MyTestCallable mMyTestCallable= new MyTestCallable(); ExecutorService mExecutorService = Executors.newSingleThreadPool(); Future mfuture = mExecutorService.submit(mMyTestCallable); try { System.out.println(mfuture.get()); } catch (Exception e) { e.printStackTrace(); } } }
此处runnable和Callable接口的区别主要体现在后者可以得到一个返回值 并可以抛出异常,而前者不可以。本示例是在一个线程池当中实现的该接口。利用
newSingleThreadPool方法去创建一个线程池
- 实现Callable接口,重写call()方法