进程与线程的区别
每个运行的程序就是一个进程,一个进程在运行时会有多个顺序执行流,每个顺序执行流就是一个线程。
进程与线程的特性
进程
1.独立性:进程是一个能独立运行的基本单位,也是独立拥有资源和调度资源的独立单位
2.动态性:进程是程序的一次执行过程,动态产生,动态消亡。
3.并发性:进程与进程之间可以一起并发执行
4.异步性:进程按各自独立的、不可预知的速度向前推进。
线程
1.线程是进程内的一个相对独立的可执行的单元。
2.线程是操作系统中基本调度单元,因此线程中应包含有调度所需要的必要信息,且在生命周期中有状态的变化。还有每个进程创建时,至少需要为该进程创建一个线程(一个进程至少拥有一个线程),否则该进程无法被调度
3.进程是被分给并拥有资源的基本单元。同一进程内的多个线程共享该进程的资源,线程并不拥有资源,只是使用父类进程拥有的资源。
创建线程的三种方式
1、继承Thread
例1:
public class myThread extends Thread {
public void run() {
for(int i=0;i<10;i++) {
System.out.println("myThread -->"+i);
}
}
}
public static void main(String[] args) {
myThread thread = new myThread();
thread.start();
for(int i=0;i<10;i++) {
System.out.println("mian -->"+i);
}
}
2、实现Runnable接口
例1:
public class myRunnable implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<30;i++) {
System.out.println("myRunnable -->"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
myRunnable myrun = new myRunnable();
Thread thr = new Thread(myrun);
thr.start();
//主线程
for(int i=0;i<30;i++) {
System.out.println("main -->"+i);
Thread.sleep(1000);
}
}
例2:使用接口内部类
Thread thr1 = new Thread(new Runnable() {//接口内部类,对象
public void run() {
for(int i=0;i<30;i++) {
System.out.println("myrunnable1-->"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
thr1.start();
3、实现Callable接口
Callable接口中的call()方法有返回值(该线程执行完不会被清出线程池,省去了线程创建与删除的时间)
Runnable接口的run()方法没有返回值
例1:
public class myCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
int result = new Random().nextInt(100);
return result;
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
myCallable mc = new myCallable();
FutureTask<Integer> task = new FutureTask<>(mc);
//FutureTask实现了RunnableFuture接口,该接口继承了Runnable
//该线程执行完不会被清出线程池,省去了线程创建与删除的时间
Thread t3 = new Thread(task);
t3.start();
System.out.println(task.get());
}