Java并发编程(一):认识线程

进程和线程

进程

进程是操作系统进行资源分配的最小单元。默认情况下,一个 App 就是一个进程,也可以为 App 开启多个进程,多个进程之间是相互独立的。

线程

线程是 CPU 调度的最小单元,任务是执行在线程中。线程依附于进程存在,当一个进程中没有可执行任务的线程时,该线程就会被回收。一个进程可以有多个线程。

CPU时间片轮转机制

坐地铁的时候可能会一边在看文章一边听歌,我们就会认为文章 APP 和 听歌 APP 是同时运行的。其实它们并不是同时运行的,系统提供了一种CPU时间片轮转机制,进程被分配到时间片它就开始工作,只不过时间片很短CPU切换的很快很频繁,这就造成了一种同时运行的假象。

百度百科的解释:

时间片轮转调度是一种最古老,最简单,最公平且使用最广的算法。每个进程被分配一个时间段,称作它的时间片,即该进程允许运行的时间。如果在时间片结束时进程还在运行,则CPU将被剥夺并分配给另一个进程。如果进程在时间片结束前阻塞或结束,则CPU当即进行切换。调度程序所要做的就是维护一张就绪进程列表,当进程用完它的时间片后,它被移到队列的末尾。

时间片轮转调度中唯一有趣的一点是时间片的长度。从一个进程切换到另一个进程是需要一定时间的–保存和装入寄存器值及内存映像,更新各种表格和队列等。假如进程切换(process switch) - 有时称为上下文切换(context switch),需要5毫秒,再假设时间片设为20毫秒,则在做完20毫秒有用的工作之后,CPU将花费5毫秒来进行进程切换。CPU时间的20%被浪费在了管理开销上。

为了提高CPU效率,我们可以将时间片设为500毫秒。这时浪费的时间只有1%。但考虑在一个分时系统中,如果有十个交互用户几乎同时按下回车键,将发生什么情况?假设所有其他进程都用足它们的时间片的话,最后一个不幸的进程不得不等待5秒钟才获得运行机会。多数用户无法忍受一条简短命令要5秒钟才能做出响应。同样的问题在一台支持多道程序的个人计算机上也会发生。

结论可以归结如下:时间片设得太短会导致过多的进程切换,降低了CPU效率;而设得太长又可能引起对短的交互请求的响应变差。将时间片设为100毫秒通常是一个比较合理的折中。

并行和并发

并行是同时进行,并发是交替进行。举个例子:并发是我一个人打三个人,要打完一个再打下一个,轮流着打(CPU轮转机制);并行就是三个人同时打三个人。

创建线程的几种方式

三种(严格意义上只有两种)。

1、继承Thread:

public class SubThread {
    @Override
    public void run() {
        super.run();
    }
}

public static void main(String[] args) {
    SubThread thread = new SubThread();
	thread.start();
}

2、实现Runnable:

public class MyRunnable implements Runnable {
    @Override
    public void run() {
    }
}

public static void main(String[] args) {
    MyRunnable runnable = new MyRunnable();
    Thread thread = new Thread(runnable);
    thread.start();
}

3、实现Callable<T>:

public class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "result";
    }
}

public static void main(String[] args) {
    MyCallable callable = new MyCallable();
    FutureTask<String> task = new FutureTask<>(callable);
    Thread thread = new Thread(task);
    thread.start();
}

为什么说严格意义上只有两种呢?

在 Thread 源码中有注释说明创建新线程有两种方式。

 * There are two ways to create a new thread of execution. One is to
 * declare a class to be a subclass of <code>Thread</code>. This
 * subclass should override the <code>run</code> method of class
 * <code>Thread</code>. An instance of the subclass can then be
 * allocated and started. 


 * The other way to create a thread is to declare a class that
 * implements the <code>Runnable</code> interface. That class then
 * implements the <code>run</code> method. An instance of the class can
 * then be allocated, passed as an argument when creating
 * <code>Thread</code>, and started.

并且查看 FutureTask 的类继承关系可知,FutureTask 实现了 RunnableFuture 接口,而 RunnableFuture 接口继承自 Runnable接口,所以 FutureTask 也是一个 Runnable。本质上与第二种 Runnable的方式没什么区别。

那这三种方式有什么区别呢?

Java 是单继承多实现,所以第一种方式扩展性比较差,第二种方式还可以实现其它的接口,但是它们共同点就是都没有返回值。第三种方式有返回值,其返回值类型是声明类中的泛型类型。

线程run和start的区别

run 方法是执行任务的地方,它就是一个普通的方法,可以多次被调用,只调用 run 方法并不会启动一个线程。而 start 方法才会真正的启动线程,start 方法会调用到 native 底层方法,然后才会调用 run 方法执行任务。start 方法只能执行一次,执行多次会抛出异常。

线程如何安全停止

1、run 方法中的任务执行完毕后线程自动停止

2、手动干扰停止。在 JDK 比较老的版本中是用 stop 方法来停止一个线程,但是现在被标为废弃了,因为它的停止方式太暴力了,不管任务执行到什么状态直接停止而没有补救措施,不能保证资源正常释放。应该使用 interrupt() 方法给线程打上一个中断标记(记住它只打标记,不会马上中断线程),线程通过isInterrupted() 方法来判断是否中断,还可以用 Thread 的静态方法 Thread.interrupted() 来判断当前线程是否被中断,不过它会将中断标记改为false。

线程串行的方式

调用thread的join()方法将线程加入到当前线程,使几个线程变成串行。

class Thread1 extends Thread {
    @Override
    public void run() {
        super.run();
        System.out.println("Thread1");
    }
}

class Thread2 extends Thread {
    @Override
    public void run() {
        super.run();
        System.out.println("Thread2");
    }
}


public static void main(String[] args) throws InterruptedException {
    Thread1 thread1 = new Thread1();
    thread1.start();
    thread1.join(); // 注意这里,必须要先start再join

    Thread2 thread2 = new Thread2();
    thread2.start();
    thread2.join();

    System.out.println("Main Thread");
}

// 打印
Thread1
Thread2
Main Thread

以上代码只有在 thread1执行完成才能执行 thread2,thread2执行完成后才能继续执行后面的main线程代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值