zoukankan      html  css  js  c++  java
  • JAVA多线程和并发基础面试问答

    wait()、notify()和notifyAll()是Object类中的方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    /**
     * Wakes up a single thread that is waiting on this object's
     * monitor. If any threads are waiting on this object, one of them
     * is chosen to be awakened. The choice is arbitrary and occurs at
     * the discretion of the implementation. A thread waits on an object's
     * monitor by calling one of the wait methods
     */
    public final native void notify();
     
    /**
     * Wakes up all threads that are waiting on this object's monitor. A
     * thread waits on an object's monitor by calling one of the
     * wait methods.
     */
    public final native void notifyAll();
     
    /**
     * Causes the current thread to wait until either another thread invokes the
     * {@link java.lang.Object#notify()} method or the
     * {@link java.lang.Object#notifyAll()} method for this object, or a
     * specified amount of time has elapsed.
     * <p>
     * The current thread must own this object's monitor.
     */
    public final native void wait(long timeout) throws InterruptedException;

       从这三个方法的文字描述可以知道以下几点信息:

      1)wait()、notify()和notifyAll()方法是本地方法,并且为final方法,无法被重写。

      2)调用某个对象的wait()方法能让当前线程阻塞,并且当前线程必须拥有此对象的monitor(即锁)

      3)调用某个对象的notify()方法能够唤醒一个正在等待这个对象的monitor的线程,如果有多个线程都在等待这个对象的monitor,则只能唤醒其中一个线程;

      4)调用notifyAll()方法能够唤醒所有正在等待这个对象的monitor的线程;

    1. 进程和线程之间有什么不同?

    一个进程是一个独立(self contained)的运行环境,它可以被看作一个程序或者一个应用。而线程是在进程中执行的一个任务。Java运行环境是一个包含了不同的类和程序的单一进程。线程可以被称为轻量级进程。线程需要较少的资源来创建和驻留在进程中,并且可以共享进程中的资源。

    2. 多线程编程的好处是什么?

    在多线程程序中,多个线程被并发的执行以提高程序的效率,CPU不会因为某个线程需要等待资源而进入空闲状态。多个线程共享堆内存(heap memory),因此创建多个线程去执行一些任务会比创建多个进程更好。举个例子,Servlets比CGI更好,是因为Servlets支持多线程而CGI不支持。

    17. volatile关键字在Java中有什么作用?

    当我们使用volatile关键字去修饰变量的时候,所以线程都会直接读取该变量并且不缓存它。这就确保了线程读取到的变量是同内存中是一致的。

  • 相关阅读:
    SonarQube
    Gerrit
    Jenkins
    Jenkins
    GitLab
    GitLab
    GitLab
    centos7配置国内yum源
    CentOS7 ping: unknown host www.baidu.com
    VirtualBox下安装CentOS7系统
  • 原文地址:https://www.cnblogs.com/yaowen/p/4849681.html
Copyright © 2011-2022 走看看