java面试之多线程

一、线程和进程之间的区别

1.进程:一个在内存中运行的应用程序。每个进程都有自己独立的一块内存空间,一个进程可以有多个线程,比如在Windows系统中,一个运行的xx.exe就是一个进程。
进程中的一个执行任务(控制单元),负责当前进程中程序的执行。一个进程至少有一个线程,一个进程可以运行多个线程,多个线程可共享数据。

2.线程:与进程不同的是同类的多个线程共享进程的堆和方法区资源,但每个线程有自己的程序计数器、虚拟机栈和本地方法栈,所以系统在产生一个线程,或是在各个线程之间作切换工作时,负担要比进程小得多,也正因为如此,线程也被称为轻量级进程。

3.区别

  • 根本区别:进程是操作系统资源分配的基本单位,而线程是处理器任务调度和执行的基本单位
  • 资源开销:每个进程都有独立的代码和数据空间(程序上下文),程序之间的切换会有较大的开销;线程可以看做轻量级的进程,同一类线程共享代码和数据空间,每个线程都有自己独立的运行栈和程序计数器(PC),线程之间切换的开销小。
  • 包含关系:如果一个进程内有多个线程,则执行过程不是一条线的,而是多条线(线程)共同完成的;线程是进程的一部分,所以线程也被称为轻权进程或者轻量级进程。
  • 内存分配:同一进程的线程共享本进程的地址空间和资源,而进程之间的地址空间和资源是相互独立的
  • 影响关系:一个进程崩溃后,在保护模式下不会对其他进程产生影响,但是一个线程崩溃整个进程都死掉。所以多进程要比多线程健壮。
  • 执行过程:每个独立的进程有程序运行的入口、顺序执行序列和程序出口。但是线程不能独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制,两者均可并发执行

二、实现方式

  1. 继承Thread类:
/**
 * 线程的实现方式一:继承Thread类
 */

public class ThreadTest {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());

        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();

        thread1.start();
        thread2.start();
    }

}
class Thread1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++){
            System.out.println(Thread.currentThread().getName());
        }
    }
}
class Thread2 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++){
            System.out.println(Thread.currentThread().getName());
        }
    }
}

2.实现Runable接口:

/**
 * 线程的实现方式二:实现Runable接口
 */
public class ThreadTest2 {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());

        Thread thread3 = new Thread(new Thread3());
        Thread thread4 = new Thread(new Thread4());

        thread3.start();
        thread4.start();
    }
}

class Thread3 implements Runnable{
    @Override
    public void run() {
            for (int i = 0; i < 10; i++){
                System.out.println(Thread.currentThread().getName());
            }
        }
}
class Thread4 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++){
            System.out.println(Thread.currentThread().getName());
        }
    }
}

两种实现方式的共同点和区别:

  • 共同点:将希望线程执行的代码块放入run()中,然后调用start()来启动
  • 区别:使用继承Thread类,类是唯一继承的原则那么该类就不能继承其他的类;而使用Runable接口的话在jiava中是可以实现的多个接口的,所以综上所述推荐使用Runable接口

三、start()和run()之间的区别

  • run()方法本身就是一个普通的方法其所有的代码块都运行在主线程中
public void run() {

    if (target != null) {

        target.run();

    }

}
//target是一个Runnable对象。run()就是直接调用Thread线程的Runnable成员的run()方法,并不会新建一个线程。
  • start()方法线程运行在各自的线程中在调用时会创建一个新的线程并启动
public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

    private native void start0();//查看open jdk

四、主线程中获取

  1. 等待主线程完成后获取:
while (threadTest3.value == null){
            Thread.sleep(5000);
        }
  1. 使用join方法
thread.join();

 /**
     * Waits at most {@code millis} milliseconds for this thread to
     * die. A timeout of {@code 0} means to wait forever.
     *
     * <p> This implementation uses a loop of {@code this.wait} calls
     * conditioned on {@code this.isAlive}. As a thread terminates the
     * {@code this.notifyAll} method is invoked. It is recommended that
     * applications not use {@code wait}, {@code notify}, or
     * {@code notifyAll} on {@code Thread} instances.
     *
     * @param  millis
     *         the time to wait in milliseconds
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public final synchronized void join(long millis)
    //从上述描述中我们可以得知join方法会一直到线程死掉

3.实现Callable接口


public class CallableTest implements Callable {
    @Override
    public Object call() throws Exception {
        String value = "我是返回值";

        System.out.println("开始执行业务逻辑");
        Thread.sleep(5000);
        System.out.println("执行业务逻辑完毕");

        return value;
    }
}
/**
 * Callabel接口实现:使用FutureTask
 */
public class CallableImk {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask = new FutureTask<String>(new CallableTest());
        new Thread(futureTask).start();

        if(!futureTask.isDone()){
            System.out.println("任务还没有完成,请稍等");
        }
        System.out.println(futureTask.get());
    }
}

4.使用线程池的方式:

public  class ThreadTest4 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<String> future = executorService.submit(new CallableTest());
        if(!future.isDone()){
            System.out.println("waiting");
        }
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }

    }
}

五、线程池

1.线程池的创建:

public class ThreadPoolExecutor extends AbstractExecutorService {
    .....
    public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
            BlockingQueue<Runnable> workQueue);
 
    public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
            BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory);
 
    public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
            BlockingQueue<Runnable> workQueue,RejectedExecutionHandler handler);
 
    public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
        BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler);
    ...
}

参数说明:

  • corePoolSize:核心池的大小,这个参数跟后面讲述的线程池的实现原理有非常大的关系。在创建了线程池后,默认情况下,线程池中并没有任何线程,而是等待有任务到来才创建线程去执行任务,除非调用了prestartAllCoreThreads()或者prestartCoreThread()方法,从这2个方法的名字就可以看出,是预创建线程的意思,即在没有任务到来之前就创建corePoolSize个线程或者一个线程。默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
  • maximumPoolSize:线程池最大线程数,这个参数也是一个非常重要的参数,它表示在线程池中最多能创建多少个线程;
  • keepAliveTime:表示线程没有任务执行时最多保持多久时间会终止。默认情况下,只有当线程池中的线程数大于corePoolSize时,keepAliveTime才会起作用,直到线程池中的线程数不大于corePoolSize,即当线程池中的线程数大于corePoolSize时,如果一个线程空闲的时间达到keepAliveTime,则会终止,直到线程池中的线程数不超过corePoolSize。但是如果调用了allowCoreThreadTimeOut(boolean)方法,在线程池中的线程数不大于corePoolSize时,keepAliveTime参数也会起作用,直到线程池中的线程数为0;
  • unit:参数keepAliveTime的时间单位,有7种取值,在TimeUnit类中有7种静态属性:
TimeUnit.DAYS;               //天
TimeUnit.HOURS;             //小时
TimeUnit.MINUTES;           //分钟
TimeUnit.SECONDS;           //秒
TimeUnit.MILLISECONDS;      //毫秒
TimeUnit.MICROSECONDS;      //微妙
TimeUnit.NANOSECONDS;       //纳秒

-workQueue:一个阻塞队列,用来存储等待执行的任务,这个参数的选择也很重要,会对线程池的运行过程产生重大影响,一般来说,这里的阻塞队列有以下几种选择:

ArrayBlockingQueue;
LinkedBlockingQueue;
SynchronousQueue;

注意:ArrayBlockingQueue和PriorityBlockingQueue使用较少,一般使用LinkedBlockingQueue和Synchronous。线程池的排队策略与BlockingQueue有关。

  • threadFactory:线程工厂,主要用来创建线程;
  • handler:表示当拒绝处理任务时的策略,有以下四种取值:
ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。 
ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。 
ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务 

六、线程同步:
1.使用syncronized关键字:使用syncronized关键字修饰的方法是对对象的加锁;也可以修饰静态方法,当修饰静态方法是是对类加锁;也可以修饰代码块如下:

 synchronized(object){
    }
    //同步是一种高开销的操作,因此应该尽量减少//同步的内容。
    //通常没有必要同步整个方法,使用synchronized代码块同步关键代码即可。

注意:关于锁的话题,我们受限于篇幅下次再聊
七:生产者和消费者:

package Thread;


public class Person {

    private String name;
    private String sex;
    private boolean isEmpty = true;

    public  synchronized void set(String  name, String sex){
        while (!isEmpty){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.name = name;
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.sex = sex;
        System.out.println("生产者:" + name + sex);

        isEmpty = false;
        this.notifyAll();
    }

    public synchronized void get(){
        if (isEmpty){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("消费: " + getName() + getSex());
        isEmpty = true;
        this.notifyAll();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

package Thread;

public class ProductConsumerTest {

    public static void main(String[] args) {
        Person person = new Person();
        new Thread(new Product(person)).start();
        new Thread(new Consumer(person)).start();
        new Thread(new Product(person)).start();
        new Thread(new Consumer(person)).start();
    }

}

class Product implements Runnable{
    private Person person;
    public Product(Person person){
        this.person = person;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            if (i % 2 == 0){
                person.set("teacher", "man");
            }else {
                person.set("mother", "women");
            }
        }

    }
}
class Consumer implements Runnable{
    private Person person;
    public Consumer(Person person){
        this.person = person;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            person.get();
        }
    }
}

参考资料:

"http://www.cnblogs.com/XHJT/p/3897440.html"

"https://www.cnblogs.com/dolphin0520/p/3932921.html"

原文地址:https://www.cnblogs.com/yjfb/p/12490595.html