07
Service(服务)
一.线程的相关概念
二.线程的生命周期
三.创建线程的方法
- 继承Thread类
public class MyThread extends Thread{
@Override
public void run() {
doSomething();
}
private void doSomething() {
System.out.println("我是一个线程中的方法");
}
}
===================================================================
===============
public class NewThread {
public static void main(String[] args) {
MyThread myThread=new MyThread();
myThread.start();
doSomething();
}
private static void doSomething() {
}
}
- 实现Runnable接口
public class RunnableThread implements Runnable{
@Override
public void run() {
doSomeThing();
}
private void doSomeThing() {
System.out.println("我是一个线程方法");
}
}
===================================================================
===============
public class NewThread {
public static void main(String[] args) {
Runnable runnable=new RunnableThread();
Thread thread=new Thread(runnable);
thread.start();
doSomething();
}
private static void doSomething() {
}
}
- 实现Callable接口和Future创建线程
public class CallableThread implements Callable<String>{
@Override
public String call() throws Exception {
doSomeThing();
return "需要返回的值";
}
private void doSomeThing() {
System.out.println("我是线程中的方法");
}
}
===================================================================
===============
public class NewThread {
public static void main(String[] args) {
Callable<String> callable=new CallableThread();
FutureTask<String> futureTask=new FutureTask<String>
(callable);
Thread thread=new Thread(futureTask);
thread.start();
doSomething();
try {
futureTask.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
private static void doSomething() {
}
}
- Service与Thread线程的区别
四.Service的生命周期

五.Service启动方式
- StartService启动Service后bindService绑定