进程和线程的概念
- 进程(Process)可以定义为“并发执行的程序在一个数据集合上的执行过程”。
- 进程是一个可以拥有资源的独立单位
- 进程是一个可以独立调度和分配的基本单位。
- 线程是进程的一个实体,是被独立调度和分派的基本单位,表示进程中的一个控制点,执行一系列指令。
通俗点讲,就好像一个班级,班级是一个进程,那么这个班级里的学生就是线程了。假设班级有500元,这个班级的学生可以是可以用这个500元的了,具体怎么使用就看班级如何分配。
生命周期
每个Java程序都有一个隐含的主线程,即main()方法。要实现多线程,必须在主线程中创建新的线程。Java语言使用Thread类及子类对象来表示线程,在它的生命周期中,线程会处于4种不同的状态。
① New (新)。
② Runnable (可运行)。
③ Blocked (被阻塞)。
④ Dead(死亡)
附:一个线程从它被创建到停止执行都要经历一个完整的生命周期。其次,当Java程序启动时,一个线程立刻运行,该线程通常叫程序的主线程( main thread ),重要的地方体现:①产生其他的子线程的线程;②通常它必须最后完成执行,因为它执行各种关闭动作。
线程的生命周期图
创建线程的多种方式
- 继承Thread类
public class First extends Thread{
String threadname;
public First(String s) {
System.out.println(" Making thread: "+ s );
threadname=s;
}
public void run() {
for(int i=0;i<3;i++) {
System.out.println(" Running thread number=" + threadname);
try {
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
First thread1=new First("1号");
First thread2=new First("2号");
thread1.start();//启动线程
thread2.start();
System.out.println("End of main!!");
}
}
运行结果
- 实现Runnable接口创建线程
public class Second implements Runnable{
String threadname;
public Second(String s) {
System.out.println(" Making thread: "+ s );
threadname=s;
}
public void run() {
for(int i=0;i<3;i++) {
System.out.println(" Running thread number=" + threadname);
try {
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread thread1,thread2;
thread1=new Thread( new Second("1号"));//创建线程
thread2=new Thread( new Second("2号"));
thread1.start();//启动线程
thread2.start();
System.out.println("End of main!!");
}
}
运行结果
- 通过线程池创建线程
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Third implements Runnable{
public void run(){
for(int i = 0; i<3; i++){
System.out.println("线程" + Thread.currentThread() + " " + i);
}
}
public static void main(String[] args)
{
ExecutorService executorService = Executors.newFixedThreadPool(5);
Third thread = new Third();
executorService.execute(thread);
}
}
运行结果
- 通过Callable和FutureTask创建线程
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Four implements Callable {//其实这个跟实现Runnable接口有点类似
String threadname;
public Four(String s) {
threadname=s;
}
public String call(){ // 与run()方法不同的是,call()方法具有返回值
System.out.println("线程名: "+Thread.currentThread().getName());
for(int i=0;i<3;i++)System.out.println("我是"+threadname+"你好"+i);
return threadname;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Four callableThread1 = new Four("小明");
Four callableThread2 = new Four("小红");
//使用FutureTask类来包装Callable实现类的对象, 且以此FutureTask对象作为Thread对象的target来创建线程.
FutureTask futureTask1 = new FutureTask<>(callableThread1);
new Thread(futureTask1).start();
FutureTask futureTask2 = new FutureTask<>(callableThread2);
new Thread(futureTask2).start();
System.out.println("主线程先做其他重要的事情");
if(!futureTask1.isDone() || !futureTask2.isDone()){
// 继续做其他事儿
for(int i=0;i<3;i++){
System.out.println("主线程在看书");
}
}
System.out.println(futureTask1.get()); // 可能会阻塞等待结果
System.out.println(futureTask2.get());
}
}
运行结果
线程之间如何传递参数
- 通过构造函数传递参数
- 通过变量和方法传递数据
- 通过回调函数传递数据
进程之间如何通信
☞ 管道( pipe ):管道是一种半双工的通信方式,数据只能单向流动,而且只能在具有亲缘关系的进程间使用。进程的亲缘关系通常是指父子进程关系。
☞ FIFO,也称有名管道 (named pipe) : 有名管道也是半双工的通信方式,但是它允许无亲缘关系进程间的通信。
☞ 信号量( semophore ) : 信号量是一个计数器,可以用来控制多个进程对共享资源的访问。它常作为一种锁机制,防止某进程正在访问共享资源时,其他进程也访问该资源。因此,主要作为进程间以及同一进程内不同线程之间的同步手段。
☞ 消息队列( message queue ) : 消息队列是由消息的链表,存放在内核中并由消息队列标识符标识。消息队列克服了信号传递信息少、管道只能承载无格式字节流以及缓冲区大小受限等缺点。
☞ 信号 ( sinal ) : 信号是一种比较复杂的通信方式,用于通知接收进程某个事件已经发生。
☞ 共享内存( shared memory ) :共享内存就是映射一段能被其他进程所访问的内存,这段共享内存由一个进程创建,但多个进程都可以访问。共享内存是最快的 IPC 方式,它是针对其他进程间通信方式运行效率低而专门设计的。它往往与其他通信机制,如信号两,配合使用,来实现进程间的同步和通信。
☞ 套接字( socket ) : 套解口也是一种进程间通信机制,与其他通信机制不同的是,它可用于不同及其间的进程通信。