2019.6.25 thread common interview questions

1. How to ensure thread safety?

Inspection point: Thread

Reference answer:

1. reasonable time schedule , to avoid the conflict access to shared resources.

2. On the parallel tasks can design appropriate strategies to ensure that the task between tasks and there is no sharing of resources , a rule designed to ensure that a customer's computing and data access will only be working to complete a thread or a working machine, and not to assign work to a client computing multiple threads to complete.

2. Please briefly explain the fundamental relationship between the state and the state about the thread?

Inspection point: Thread

Reference answer:

Running which indicates the operating state,

Runnable represents the ready state (everything is ready, only a strong CPU),

Blocked represents blocked state, blocking state there are a variety of circumstances, it may be because the call wait () method enters the waiting pool, the synchronization method may also be performed or the like into the locked synchronized block pool, or a call sleep () method or join () method waits dormant or end of another thread, or because of the occurrence of an I / O interrupt.

3. Please explain what is the thread pool (thread pool)?

Inspection point: the thread pool

Reference answer:

In object-oriented programming, creating and destroying objects is very time consuming, because an object is created to get more memory resources or other resources. Especially in Java virtual machine will attempt to track every object to make garbage collection after the object is destroyed. Therefore, to improve the efficiency of the service program is a means to minimize the number of creating and destroying objects, especially some very resource-intensive objects are created and destroyed, which is why "pooled resources" techniques. As the name suggests the thread pool is created in advance a number of executable threads into a pool (container), the time needed to obtain the thread from the pool do not create your own, do not need to be destroyed after use but the thread back into the pool, thereby reducing the creation and destruction overhead thread object .
Java 5+ The Executor interface defines a thread of execution tool. It is a subtype that is the thread pool interface is a ExecutorService. To configure a thread pool is more complex, especially for the principle of the thread pool is not very clear, the thus provides static factory method in the face Executors tools, generating some common thread pool, as follows:
- newSingleThreadExecutor : Creating a single-threaded thread pool. This is only a thread pool thread work, which is equivalent to a single-threaded serial execution of all tasks. If this thread only because of abnormal termination, then there will be a new thread to replace it. This thread pool to ensure that the order of execution of all tasks presented to the order of tasks.
- newFixedThreadPool: create a thread pool of fixed size. Each time you submit a task to create a thread, until the thread pool thread to reach the maximum size. Once the size of the thread pool reaches the maximum will remain unchanged, because if a thread execution abnormal end, the thread pool would add a new thread.
- newCachedThreadPool: Creating a cached thread pool. If the size of the thread pool threads exceeds the processing tasks required, it will recover partially free (60 seconds does not perform the task) threads, when the number of tasks, this thread pool and intelligently add a new thread to handle the task. This thread pool do not restrict the size of the thread pool, thread pool thread maximum size depends entirely on the size of the operating system (or JVM) that can be created.
- newScheduledThreadPool: Create an unlimited size of the thread pool. This thread pool to support the timing and the need to perform tasks periodically.
- newSingleThreadExecutor: create a thread pool of single-threaded. This thread pool to support the timing and the need to perform tasks periodically.

4 illustrates a synchronous and asynchronous

Inspection point: Thread

Reference answer:

If there is a critical resource system (the number of resources is less than the number of threads of resource competition for resources), for example, it may be read after writing the data to another thread, or is reading data may have been written by another thread, then these data must be synchronized access (database exclusive lock operation is the best example). When the application calls the method takes a long time to execute on the object, and do not want the program to wait for the process to return, you should use asynchronous programming, using asynchronous approach in many cases tend to be more efficient. In fact, the so-called synchronization refers to the blocking operation, and is non-blocking asynchronous operation.

5. Please tell us about thread synchronization and thread scheduling related methods.

Inspection point: Thread Synchronization

Reference answer:

- wait (): make a thread in waiting (blocked) state, and release the lock held by the object;
- SLEEP (): make a running thread in a sleep state, is a static method, this method is called to process InterruptedException anomaly;
- the Notify (): wake up a thread in a wait state, of course, when this method is called, does not exactly wake up one thread wait state, but by the JVM which thread wakes up and has nothing to do with the priority ;
- notityAll (): wake up all the threads in a wait state, the method will not object to lock all the threads, but to let them compete, only to get a lock thread into the ready state;
by lock provides an explicit interface lock mechanism (explicit lock), enhances flexibility and coordination of the thread. Lock interface defined in the lock (Lock ()) and unlocking (UNLOCK ()) method, while also providing newCondition () method to generate Condition objects for communication between threads; In addition, Java 5 also provides a signal the amount of mechanisms (semaphore), semaphores can be used to limit the number of accesses to a shared resource threads. Before access to a resource, a thread must obtain the semaphore permission (call Semaphore object acquire () method); after the completion of access to resources, the thread must return the license to the semaphore (call Semaphore object release () method) .

Will 6. When a thread enters a synchronized method A after the object, other threads can access this object synchronized method B?

Inspection point: Thread

Reference answer:

Can not. Asynchronous method other threads can access the object, it can not enter synchronization method. Because the non-static method synchronized modifier required to perform a method to obtain an object when the lock , if method A description of the object has entered the lock has been removed, then tried to enter the thread B method can only lock in the pool, etc. (note not wait Oh lock pool) waiting objects.

7. Please describe briefly threads sleep () method and the yield () method What is the difference?

Inspection point: Thread

Reference answer:

①sleep () method to other threads to run when the opportunity without regard to priority thread , so give opportunity to the low priority thread to run; yield () method will only give the same priority or higher priority thread to run opportunity;

After the execution thread ② sleep () method into the blocked (blocked) state, and after the implementation of yield () method into the ready (ready) state;
③ sleep () method declaration throws InterruptedException , while the yield () method does not declare any exception ;
④ SLEEP () method than the yield () method (associated with the operating system, CPU scheduling) more portable.

8. Please answer the following questions:

The first question: Java There are several ways to implement a thread?

There are two methods, namely, inheritance Thread class and implement Runnable.

The second question: What Keywords synchronization method modified?

Modified synchronization method with the synchronized keyword,

 The third question: stop () and suspend () method Why not recommended, please explain why?

Against the use of stop (), because it is not safe. It will release all locks acquired by a thread, and if the object is in an inconsistent state, so other threads can check and modify them in that state. The result is difficult to check out the real problem. suspend () method is easy to deadlock. Call to suspend () when the target thread will stop, but they still hold locked in before obtained. At this point, any other thread can access a locked resources unless it is "suspended" thread to resume operation. For any thread, if they want to resume the target thread, while any attempt to use a resource locking, it will cause a deadlock. So you should not use suspend (), but should put a sign in his class Thread, the thread should be pointed out that active or suspended. If the flag indicates that the thread should hang, they use wait () command it enters the wait state. If the flag indicates that the thread should be restored, then use a notify () to restart the thread.

9. Please explain what each multi-threading and synchronization There are several implementations, and details of these implementations are what?  

Inspection point: Thread

Reference answer:

There are two ways to achieve multi-threaded, are inheriting the Thread class and implement Runnable.

There are two aspects to achieve synchronization, which are synchronized, wait and notify.

10. Please state thread synchronization method you know

Inspection point: Thread Synchronization

Reference answer:

wait (): make a thread in a wait state, and releases the lock held by the object.
sleep (): make a running thread in a sleep state, it is a static method call this method to capture InterruptedException exception.
notify (): wake up a thread in a wait state, noting that at the time this method is called, does not exactly wake up one thread wait state, but which is determined by the JVM thread wakes up, but not by priority.
Allnotity (): wake up a thread into a wait state at all, note that not all wake up threads to lock an object, but let them compete.

11. Start a thread is run () or start ()?

Inspection point: JAVA thread

Reference answer:

Start a thread that calls start () method , the thread is represented by the virtual processor can run the state, which means that it can schedule and execute by the JVM. This does not mean that the thread will run immediately. run () method can produce signs must quit to stop a thread.

12. Use inner class Thread Design of threads, wherein each of the two threads 1 j is incremented, the other two thread 1 j is decremented.

Inspection point: JAVA thread

Reference answer:

public class ThreadTest1{
    private int j;
    public static void main(String args[]){
        ThreadTest1 tt=new ThreadTest1();
        Inc inc=tt.new Inc();
        Dec dec=tt.new Dec();
        for(int i=0;i<2;i++){
            Thread t=new Thread(inc);
            t.start();
            t=new Thread(dec);
            t.start();
        }
    }
    private synchronized void inc(){
        j++;
        System.out.println(Thread.currentThread().getName()+"-inc:"+j);
    }
    private synchronized void dec(){
        j--;
        System.out.println(Thread.currentThread().getName()+"-dec:"+j);
    }
    class Inc implements Runnable{
        public void run(){
            for(int i=0;i<100;i++){
                inc();
             }
        }
    }
    class Dec implements Runnable{
        public void run(){
            for(int i=0;i<100;i++){
                dec();
            }
        }
    }
}

13. Please explain thread synchronous and asynchronous similarities and differences? Please give examples and under what circumstances to use synchronous and asynchronous?

Inspection point: Thread Synchronization

Reference answer:

If the data between threads will be shared . For example, it may be read by another thread after the writing of data, or data is being read may have been written by another thread, then the data is shared data, access must be synchronized.
When the application calls the method takes a long time to execute on the object, and do not want when the program to wait for the process to return , you should use asynchronous programming, using asynchronous approach in many cases tend to be more efficient.

14. Please explain sleep () and wait () What is the difference?

Inspection point: Thread

Reference answer:

sleep is a thread class method (Thread), leading to this thread to suspend the specified time, the opportunity to perform other threads, but monitoring status remains, to the post will be automatically restored. Call sleep will not release the object lock.
wait is the Object class method, the object method call to this wait cause the thread to give the object lock, waiting to enter the pool waiting for a lock for this object, and only issued after notify method (or notifyAll) for this thread to lock this object before entering the target pool to get ready object lock into operation.

15. Please explain in (Monitor) internal watchdog, it is how to do thread synchronization? In the program you should do what level of sync it? 

Inspection point: JAVA Thread Synchronization

Reference answer:

Monitor and lock in the Java virtual machine is a piece of use.

Monitor monitors a sync block, to ensure that only one thread is executing synchronized block.

Each of the monitors and associated with an object reference. Thread is not allowed to perform synchronization code before acquiring the lock.

16. Please analyze what is the difference synchronization method and synchronized block is?

Investigation Point: JAVA code block synchronization

Reference answer:

Difference: 
a synchronization method using this default as a lock current class or class object; 
synchronization code blocks may be selected to be any lock, to be more fine-grained than synchronous methods, we can select only the portion of the code synchronization synchronization problem occurs instead of the whole method.

17. Please describe in detail about the threads from creation to the death of several states have what?

Inspection point: JAVA thread state

Reference answer:

1. Create (new): create a new thread object. 
2. run (runnable): After the thread object is created, other threads (such as main thread) calls the start () method of the object. The thread state is located runnable threads in the pool, waiting to be selected thread scheduling, acquiring the right to use the cpu. 
3. Run (running): runnable (Runnable) obtained threads of cpu time slice (timeslice), execution of program code. 
4. blocked (block): blocking state is the thread for some reason to give up the right to use the cpu, that is let out of the cpu timeslice, temporarily stop running. Until the thread becomes runnable (runnable) state, you have a chance to get cpu timeslice to run (running) state again. Where blocking three categories: 
. (A) blocked waiting for: o a thread of execution run (running) a wait () method, JVM will thread into the wait queue (waitting queue) in. 
(B) synchronous blocking: thread running (running) when acquiring synchronization lock object, if the synchronization lock is occupied by another thread, the JVM will lock into the thread pool (lock pool) in. 
(3) Other blocking: Run (running) thread execution Thread sleep (long ms) or t join () method, or issue the I / O request, the JVM will set the thread is blocked. When sleep () timeout, the Join () wait for a thread to terminate or times out, or when the I / O processing is complete, the thread may be re-run into (Runnable) state. 
5. death (dead): Thread run (), main () method has finished executing, or due to abnormal withdrew from the run () method, the thread end of the life cycle. Thread of death can not be resurrected again.

18. Create a thread in several different ways? Which do you prefer? why?

Inspection point: JAVA thread

Reference answer:

There are three ways to create threads: 
inheritance Thread class 
implement Runnable 
application can use the framework to create a thread pool Executor 
implement Runnable this way more popular, because it does not need to inherit the Thread class. In the case of application design we have inherited the other object, which requires multiple inheritance (but Java does not support multiple inheritance), only interfaces. At the same time, the thread pool is also very efficient, easy to implement and use.

19. Please explain the multi-threaded Java callback What does it mean?

Inspection point: JAVA multithreading

Reference answer:

The so-called callback, call the C program is the customer service program S is one of the methods A, S and then at some point in turn invoke a method in C B, for C, this B will be called callback method.

20. Please list what started the thread, which has several ways, after re-explain what are the kind of thread pool?

Inspection point: the thread pool

Reference answer:

① start the thread has the following three ways:

First, create a Thread class inheritance Thread class

(1) define a subclass of the Thread class and override the run method of the class, method body that represents the run method of the thread to complete the task. Thus the run () method is called executable.

(2) create an instance of a subclass of Thread, the thread object is created.

(3) the calling thread object's start () method to start the thread.

Code:

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

package com.thread;

public class FirstThreadTest extends Thread{

    int i = 0;

    //重写run方法,run方法的方法体就是现场执行体

    public void run()

    {

        for(;i<100;i++){

        System.out.println(getName()+"  "+i);

         

        }

    }

    public static void main(String[] args)

    {

        for(int i = 0;i< 100;i++)

        {

            System.out.println(Thread.currentThread().getName()+"  : "+i);

            if(i==20)

            {

                new FirstThreadTest().start();

                new FirstThreadTest().start();

            }

        }

    }

  

}

The above code Thread.currentThread () method returns the currently executing thread object. GetName () method returns the name of the thread that calls the method.

Second, create threads through the Runnable interface class

(1) Definition runnable interface implementation class, interface and override the run () method, the method body run () method of the same thread of execution threads.

(2) create an instance of Runnable implementation class, and so as an example of a target to create Thread Thread object, the Thread object is the real thread object.

(3) the calling thread object's start () method to start the thread.

Code:

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

26

27

28

29

package com.thread;

  

public class RunnableThreadTest implements Runnable

{

  

    private int i;

    public void run()

    {

        for(i = 0;i <100;i++)

        {

            System.out.println(Thread.currentThread().getName()+" "+i);

        }

    }

    public static void main(String[] args)

    {

        for(int i = 0;i < 100;i++)

        {

            System.out.println(Thread.currentThread().getName()+" "+i);

            if(i==20)

            {

                RunnableThreadTest rtt = new RunnableThreadTest();

                new Thread(rtt,"新线程1").start();

                new Thread(rtt,"新线程2").start();

            }

        }

  

    }

  

}

三、通过Callable和Future创建线程

(1)创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。

(2)创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。

(3)使用FutureTask对象作为Thread对象的target创建并启动新线程。

(4)调用FutureTask对象的get()方法来获得子线程执行结束后的返回值

代码:

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

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

package com.thread;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.FutureTask;

  

public class CallableThreadTest implements Callable<Integer>

{

  

    public static void main(String[] args)

    {

        CallableThreadTest ctt = new CallableThreadTest();

        FutureTask<Integer> ft = new FutureTask<>(ctt);

        for(int i = 0;i < 100;i++)

        {

            System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);

            if(i==20)

            {

                new Thread(ft,"有返回值的线程").start();

            }

        }

        try

        {

            System.out.println("子线程的返回值:"+ft.get());

        catch (InterruptedException e)

        {

            e.printStackTrace();

        catch (ExecutionException e)

        {

            e.printStackTrace();

        }

  

    }

  

    @Override

    public Integer call() throws Exception

    {

        int i = 0;

        for(;i<100;i++)

        {

            System.out.println(Thread.currentThread().getName()+" "+i);

        }

        return i;

    }

  

}

②线程池的种类有:

Java通过Executors提供四种线程池,分别为:
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

21.请简要说明一下JAVA中cyclicbarrier和countdownlatch的区别分别是什么?

考察点:线程

参考回答:

CountDownLatch和CyclicBarrier都能够实现线程之间的等待,只不过它们侧重点不同:

CountDownLatch一般用于某个线程A等待若干个其他线程执行完任务之后,它才执行;

而CyclicBarrier一般用于一组线程互相等待至某个状态,然后这一组线程再同时执行;

另外,CountDownLatch是不能够重用的,而CyclicBarrier是可以重用的。

22. 请说明一下线程池有什么优势?

考察点:线程池

参考回答:

第一:降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。

第二:提高响应速度。当任务到达时,任务可以不需要等到线程创建就能执行。

第三:提高线程的可管理性,线程是稀缺资源,如果无限制地创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一分配、调优和监控。

23. 请回答一下Java中有几种线程池?并且详细描述一下线程池的实现过程

考察点:线程池

参考回答:

1、newFixedThreadPool创建一个指定工作线程数量的线程池。每当提交一个任务就创建一个工作线程,如果工作线程数量达到线程池初始的最大数,则将提交的任务存入到池队列中。 
2、newCachedThreadPool创建一个可缓存的线程池。这种类型的线程池特点是: 
1).工作线程的创建数量几乎没有限制(其实也有限制的,数目为Interger. MAX_VALUE), 这样可灵活的往线程池中添加线程。 
2).如果长时间没有往线程池中提交任务,即如果工作线程空闲了指定的时间(默认为1分钟),则该工作线程将自动终止。终止后,如果你又提交了新的任务,则线程池重新创建一个工作线程。 
3、newSingleThreadExecutor创建一个单线程化的Executor,即只创建唯一的工作者线程来执行任务,如果这个线程异常结束,会有另一个取代它,保证顺序执行(我觉得这点是它的特色)。单工作线程最大的特点是可保证顺序地执行各个任务,并且在任意给定的时间不会有多个线程是活动的 。 
4、newScheduleThreadPool创建一个定长的线程池,而且支持定时的以及周期性的任务执行,类似于Timer。(这种线程池原理暂还没完全了解透彻) 

24.请说明一下Java中都有哪些方式可以启动一个线程?

考察点:线程

参考回答:

1. 继承自Thread类

2. 实现Runnable接口

3.即实现Runnable接口,也继承Thread类,并重写run方法

25. 请列举一下创建线程的方法,并简要说明一下在这些方法中哪个方法更好,原因是什么?

考察点:线程

参考回答:

需要从Java.lang.Thread类派生一个新的线程类,重载它的run()方法;

实现Runnalbe接口,重载Runnalbe接口中的run()方法。

实现Runnalbe接口更好,使用实现Runnable接口的方式创建的线程可以处理同一资源,从而实现资源的共享.

26. 请简短说明一下你对AQS的理解。

考察点:多线程

参考回答:

AQS其实就是一个可以给我们实现锁的框架
内部实现的关键是:先进先出的队列、state状态
定义了内部类ConditionObject
拥有两种线程模式独占模式和共享模式。
在LOCK包中的相关锁(常用的有ReentrantLock、 ReadWriteLock)都是基于AQS来构建,一般我们叫AQS为同步器。

27. 请简述一下线程池的运行流程,使用参数以及方法策略等

考察点:线程池

参考回答:

线程池主要就是指定线程池核心线程数大小,最大线程数,存储的队列,拒绝策略,空闲线程存活时长。当需要任务大于核心线程数时候,就开始把任务往存储任务的队列里,当存储队列满了的话,就开始增加线程池创建的线程数量,如果当线程数量也达到了最大,就开始执行拒绝策略,比如说记录日志,直接丢弃,或者丢弃最老的任务。

28. 线程,进程,然后线程创建有很大开销,怎么优化?

考察点:多线程

参考回答:

可以使用线程池。

29. 请介绍一下什么是生产者消费者模式?

考察点:线程

参考回答:

生产者消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一存储空间,生产者向空间里生产数据,而消费者取走数据。

优点:支持并发、解耦。

29. 请简述一下实现多线程同步的方法?

考察点:多线程

参考回答:

可以使用synchronized、lock、volatile和ThreadLocal来实现同步。

30. 如何在线程安全的情况下实现一个计数器?

考察点:多线程

参考回答:

可以使用加锁,比如synchronized或者lock。也可以使用Concurrent包下的原子类。

31. 多线程中的i++线程安全吗?请简述一下原因?

考察点:多线程

参考回答:

不安全。i++不是原子性操作。i++分为读取i值,对i值加一,再赋值给i++,执行期中任何一步都是有可能被其他线程抢占的。

Guess you like

Origin blog.csdn.net/qq_31194443/article/details/93639229