一、进程和线程
进程是程序的一次动态执行过程,它需要经历从代码加载,代码执行到执行完毕的一个完整的过程;
线程是比进程更小的执行单位,线程是进程的基础之上进行进一步的划分;
一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务
二、线程的生命周期
运行状态:
- 1.CPU时间分配结束——就绪状态
- 2.sleep(*),进入睡眠——阻塞状态——(时间到)——就绪状态
- 3.wait(),进入等待——阻塞状态——(notify()唤醒)——就绪状态
- 4.run()结束或stop()——死亡状态
三、创建线程
1.通过继承Thread类来创建一个线程
class ThreadTest extends Thread{
public void run(){
for(int i = 0;i<100;i++)
{
System.out.println("线程3"+i);
}
}
}
// 外部方法,实现Thread类
public class ThreadDemo {
public static void main(String[] args) {
ThreadTest thread = new ThreadTest ();
thread.start();
}
}
特点:实现简单,单继承
2.通过实现Runnable接口来创建Thread线程
class RunnableTest implements Runnable{
public void run(){
for(int i = 0;i<100;i++)
{
System.out.println("线程4"+i);
}
}
}
// 外部方法,实现Runnable类
public class ThreadDemo {
public static void main(String[] args) {
RunnableTest runnable = new RunnableTest ();
Thread t1 =new Thread(runnable);
t1.start();
}
}
特点:可实现多个接口;多个线程可以使用同一个target对象,适合多个线程处理同一份资源的情况。
要访问当前线程,必须调用Thread.currentThread()方法。
3.通过Callable和Future接口创建线程
public class ThreadTest {
public static void main(String[] args) throws Exception {
testCallable();
}
public static void testCallable() throws Exception {
Callable callable = new MyThreadCallable();
FutureTask task = new FutureTask(callable);
new Thread(task).start();
System.out.println(task.get());
Thread.sleep(10);//等待线程执行结束
//task.get() 获取call()的返回值。若调用时call()方法未返回,则阻塞线程等待返回值
//get的传入参数为等待时间,超时抛出超时异常;传入参数为空时,则不设超时,一直等待
System.out.println(task.get(100L, TimeUnit.MILLISECONDS));
}
}
class MyThreadCallable implements Callable {
public Object call() throws Exception {
System.out.println("通过实现Callable,线程号:" + Thread.currentThread().getName());
return 10;
}
}
特点:与Runnable其他特点相同,独有特点为有返回值,可以抛出异常