Integration of multi-threaded face questions

(1) Java programmer to write a program would lead to deadlock

package 设计模式.Single_Thread_Execution.多线程面试题;

import java.util.concurrent.TimeUnit;

/**
 * @author Heian
 * @time 19/01/23 10:42
 * @copyright(C) 2019 深圳市北辰德科技股份有限公司
 * 用途:手写一个死锁程序
 */
public class DeadLock {
    /**
     * 造成死锁的原因:线程一持有A对象的锁等待获取B对象锁(没拿到不允许结束生命周期),线程二持有对象B的锁等待获取A的锁,而A,B只有一个,就会出现死锁
     * 典故:科学家吃面  A科学家想吃面但是只拿到了叉子,B科学家也想吃面,但是只拿到了刀子,于是两人相互等待着
     */
    private static final Object A = new Object ();
    private static final Object B = new Object ();
    
    //持有A的锁,想去拿B的锁,完成吃面
    public void getB() {
        synchronized (A){
            System.out.println (Thread.currentThread ().getName () + "拿到了A对象的锁");
            try {
                TimeUnit.SECONDS.sleep (1);
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }
            synchronized (B){
                System.out.println (Thread.currentThread ().getName () + "拿到了B对象的锁");
            }
        }
    }
    //持有B的锁,想去拿A的锁,完成吃面
    public void getA(){
        synchronized (B){
            System.out.println (Thread.currentThread ().getName () + "拿到了B对象的锁");
            synchronized (A){
                System.out.println (Thread.currentThread ().getName () + "拿到了A对象的锁");
            }
        }
    }

    public static void main(String[] args) {
        DeadLock deadLock = new DeadLock ();
        new Thread (() -> {
            while(true){
                deadLock.getB ();
            }
        },"线程一").start ();

        new Thread (() -> {
            while(true){
                deadLock.getA ();
            }
        },"线程二").start ();

    }

}

(2) What is the spin

    Many synchronized code inside just some very simple code, very fast execution time, then wait for the thread lock might be a less worthy of operation, because the thread blocking issues related to the user mode and kernel mode switching. Since the code execution inside the synchronized very fast, let's wait for the lock thread is not blocked, but do busy circulating in the border synchronized, this is spin. If you do not find that many times get busy cycle lock, and then blocked, this may be a better strategy.

(3) What is CAS

    CAS, called the Compare and Swap, i.e. comparison - alternatively; CAS mechanism uses three basic operand: memory address V, old expected value A, to modify the new value B, when and only when the anticipated value of A and the memory V value is the same, only the memory value is modified to B and returns true, otherwise do nothing and returns false. CAS is to get the data through an infinite loop, if the first round of the cycle, a thread gets inside the address value is modified b-threaded, then a thread needs to spin cycle to the next possible opportunity to perform.

    synchronized belong pessimistic locking, pessimistic concurrency program considered serious, so to prevent sticking, CAS belong optimistic locking, concurrency optimistic that the program is not so serious, so let's continue to retry the update thread

(4) What is the optimistic and pessimistic locking

    Optimistic locking: As its name suggests, for thread safety issues between concurrent operations generated optimistic state, optimistic locking that competition does not always happen, so it does not need to hold the lock, the comparison - replace these two actions as an atomic operation attempts to modify variables in memory, if said conflict fails, then there should be a corresponding retry logic, e.g. CAS.

    Pessimistic lock: or, as its name suggests, for thread safety issues between concurrent operations generated a pessimistic state, pessimistic locking that competition will always happen, so every time a resource operation, will hold an exclusive lock, like synchronized, just-do, directly on the lock on the operating resources, such as syncronized.

 (5) What is the AQS

    Briefly about AQS, AQS full name AbstractQueuedSychronizer, should be translated abstract queue synchronizer. If the foundation is java.util.concurrent CAS, then AQS is the core of the contract and the entire Java, ReentrantLock, CountDownLatch, Semaphore, etc., use it. AQS actually connected in the form of two-way queue of all of Entry, say ReentrantLock, all waiting threads are placed in a two-way Entry and even into the queue in front of a thread uses ReentrantLock Well, the fact of the first two-way queue Entry to start a run. AQS defines all operations on the two-way queue, but only open tryLock and tryRelease method for developers to use, developers can rewrite tryLock and tryRelease method based on their implementation, in order to realize their concurrent function.

(6) how to make a thread execution order

package AtomicIntegerTest;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author Heian
 * @time 19/03/08 23:33
 * @copyright(C) 2019 深圳市北辰德科技股份有限公司
 * 用途:如何使得线程顺序进行
 */
public class JoinAndThreadPool {

    static ExecutorService executorService = Executors.newSingleThreadExecutor ();//单例线程池

    public static void main(String[] args)  {
        //方法一:使用Thread类中的join方法,使得主线程必须等待子线程执行完成执行完
        IntStream.range (0,10).forEach (i ->{
            Thread th = new Thread (() -> System.out.println (Thread.currentThread ().getName () + "执行了"),"线程" + i);
            try {
                th.start ();
                th.join ();// 加了此方法线程方能顺序执行
           } catch (InterruptedException e) {
                e.printStackTrace ();
            }
        } );
        // 线程0执行了 线程1执行了 线程2执行了 线程3执行了 线程4执行了 线程5执行了 线程6执行了 线程7执行了 线程8执行了 线程9执行了
//可以看出,Join方法实现是通过wait(小提示:Object 提供的方法)。 当main线程调用t.join时候,main线程会获得线程对象t的
//锁(wait 意味着拿到该对象的锁),调用该对象的wait(等待时间),直到该对象唤醒main线程 ,比如退出后。这就意味着main 线程调用t.join时,必须能够拿到线程t对象的锁。
//join方法  只会暂停当前main线程,不会影响其它线程的独立运行,我这里是每创建一个线程就暂停main创建第二个,所以会依次进行


        //方法二:使用单例线程池,用唯一的工作线程执行任务,保证所有任务按照指定顺序执行
        Thread thread1 = new Thread (() -> {
            try {
                TimeUnit.SECONDS.sleep (1);
                System.out.println (Thread.currentThread ().getName () + "执行了1");
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }
        },"线程一");
        Thread thread2 = new Thread (() -> {
            try {
                TimeUnit.SECONDS.sleep (1);
                System.out.println (Thread.currentThread ().getName () + "执行了2");
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }
        },"线程二");
        Thread thread3 = new Thread (() -> {
            try {
                TimeUnit.SECONDS.sleep (1);
                System.out.println (Thread.currentThread ().getName () + "执行了3");
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }
        },"线程三");
        executorService.submit (thread1);
        executorService.submit (thread2);
        executorService.submit (thread3);
        executorService.shutdown ();
        //pool-1-thread-1执行了1
        //pool-1-thread-1执行了2
        //pool-1-thread-1执行了3
    }


}

(7) thread, which has several state?

    new: create a thread object

    runnable: ready state (wait cpu scheduling)

    runnring: operating status

    blocked: blocking state (e.g., wait, sleep, was added in order to obtain the lock lock queue, io blockages, etc.)

    terminated: terminated state

(8) wait sleep (Thread class) and objects () the difference?

      sleep is a static method of the Thread class, this method is called the current thread will pause the specified time, it will switch cpu time slices to other threads, but the object remains, will automatically return to the ready state after the sleep time.

     wait is a method of the Object class, call the wait method will give up the object lock, thread suspended, waiting to enter the target cell, only calls notify or notifyAll method to wake up a thread waiting to enter the pool and other pools lock, if the thread object to regain you can enter the ready state.

(9) A thread synchronization method of an object entering a, whether the thread B can enter the synchronization method this object B?

    Asynchronous methods can not, other threads can access the object, thread A enters a description of the synchronization method lock has been removed, then the other thread tries to enter the synchronization method b can only wait for a lock objects in the lock such as the pool.

sleep method and the yield method (10) threads What is the difference?

    sleep method to other threads to run without considering the priority of the thread, so give low priority thread running opportunities, yield method will only give the same priority or higher priority thread given the opportunity to run; sleep thread execution method blocking state, while the yield after the execution method into a ready state, sleep interruptedException throw an exception, but the method does not yield any exception statement.

    

 

 

Guess you like

Origin blog.csdn.net/qq_40826106/article/details/86607122