多线程学习总结1
进程与程序
程序:程序只是一组指令的有序集合,是一个静态的实体。
进程:是程序在某个数据集上的执行,是一个动态的实体,有生命周期,反映了一个程序在一定的数据集上运行的全部动态过程。
关系:程序与进程二者并不一一对应,一个程序执行在不同的数据集上就成为了不同的进程,可以用进程控制块来唯一地标识每个进程。一般来说,一个进程肯定有且只有一个与之对应的程序,而一个程序有可能没有与之对应的程序,也可能有多个进程与之对应(运行在几个不同的数据集上)。
线程:是进程内一个相对独立的、可调度的执行单元,又称为轻量级进程。线程必须拥有父进程。系统没有为线程分配资源,它与进程中的其他线程共享该进程的共享资源。同一进程的不同线程共享相同的地址空间,它们可以访问相同的变量与对象,实现线程间的位置共享。线程可以彼此独立运行,一个程序可以同时使用多个线程来完成不同的任务。多一个线程就会多一个栈。
多线程
多线程程序是指一个程序含有多个执行流,这是实现并发机制的有效手段。
并发机制:是指在一个时间段内,有几个程序都处于已启动运行到运行完毕期间,这几个程序都是在同一个处理机上运行,但是在任一个时刻内只有一个程序在处理机上运行。
构造线程的三种方法
1.构建Thread子类对象,即构建一个继承Thread类的对象,重写run()方法
public class MyThreadTest extends Thread{
String threadPrint;
public MyThreadTest(String threadPrint){
this.threadPrint = threadPrint;
}
@Override
public void run(){
System.out.println("Print Action!"+ this.threadPrint);
int i = 0;
while(i<3){
System.out.println("张三");
System.out.println("李四");
System.out.println("王五");
i++;
}
System.out.println(this.threadPrint+" Print is Done!");
}
}
public class Test {
public static void main(String []args){
System.out.println("Test Start!");
MyThreadTest t1 = new MyThreadTest("thread1");
t1.start();
MyThreadTest t2 = new MyThreadTest("thread2");
t2.start();
MyThreadTest t3 = new MyThreadTest("thread3");
t3.start();
System.out.println("Print is Done!");
}
}
结果:
Thread — Postimages (postimg.cc)
2.继承Runnable接口,重写run()\
public class MyRunnable implements Runnable{
String threadAge;
public MyRunnable(String threadAge){
this.threadAge = threadAge;
}
public void run(){
System.out.println("Thread start:"+this.threadAge);
for(int i = 10;i<13;i++){
System.out.println("年龄: "+i);
}
System.out.println("Thread stop:"+this.threadAge);
}
}
public class Test {
public static void main(String[] args){
System.out.println("Test start!");
Runnable r1 = new MyRunnable("thread1");
Thread t1 = new Thread(r1);
t1.start();
Runnable r2 = new MyRunnable("thread2");
Thread t2 = new Thread(r2);
t2.start();
Runnable r3 = new MyRunnable("thread3");
Thread t3 = new Thread(r3);
t3.start();
System.out.println("Test is Done");
}
}
结果:
Thread2 — Postimages (postimg.cc)
使用Callable接口,重写call()
与Runnable接口不同,Callable接口重写的是call(),Callable接口执行完后可返回值,Runnable接口执行完后不能返回值,call()还可以返回异常等。