cool hit counter Java multi-threaded interview questions organized 1) What are threads?_Intefrankly

Java multi-threaded interview questions organized 1) What are threads?


1) What are threads?

A thread is the smallest unit of computing scheduling that the operating system can perform; it is contained within the process and is the actual unit of operation within the process. Programmers can use it for multi-processor programming and you can use multiple threads to speed up computationally intensive tasks. For example, if it takes one thread 100 milliseconds to complete a task, it takes only 10 milliseconds to complete the change with ten threads. Java offers excellent support for multithreading at the language level, and it's a great selling point.

2) What is the difference between threads and processes?

线程是进程 of子集,一个进程可以有很多线程,每条线程并行执行不同 of任务。不同 of进程使用不同 of内存空间,而所有 of线程共享一片相同 of内存空间。别把它 harmony栈内存搞混,每个线程都拥有单独 of栈内存用来存储本地数据。

3) How to implement threads in Java?

1)java.lang.Thread 类 of实例就是一个线程但是它需要调用java.lang.Runnable接口来执行,

2) thanks to线程类本身就是调用 ofRunnable接口所以你可以继承java.lang.Thread 类或者直接调用Runnable接口来重写run()方法实现线程。

3). Implement the Callable interface to create Thread threads via the FutureTask wrapper

The Callable interface (which also has only one method) is defined as follows.

public interface Callable<V>   { 
  V call() throws Exception;   } 
public class SomeCallable<V> extends OtherClass implements Callable<V> {

    @Override
    public V call() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

}

4).使用ExecutorService、Callable、Future实现有返回结果 of线程

ExecutorService、Callable、Future三个接口实际上都是属于Executor框架。返回结果 of线程是在JDK1.5中引入 of新特征,有了这种特征就不需要再 because of了得到返回值而大费周折了。而且自己实现了也可能漏洞百出。

Tasks that can return values must implement the Callable interface. Similarly, tasks with no return value must implement the Runnable interface.

After executing a Callable task, you can get a Future object, and call get on that object to get the Object returned by the Callable task.

Note: the get method is blocking, i.e.: the thread returns no result, and the get method will always wait.

Combined with the thread pool interface ExecutorService you can implement the legendary multi-threading with returned results.

5).Thread 类中 ofstart() harmony run() 方法有什么区别

1.start()方法来启动线程,真正实现了多线程运行。这时无需等待run方法体代码执行完毕,可以直接继续执行下面 of代码;通过调用Thread类 ofstart()方法来启动一个线程,这时此线程是处于就绪状态,并没有运行。然后通过此Thread类调用方法run()来完成其运行操作 of,这里方法run()称 because of线程体,它包含了要执行 of这个线程 of内容,Run方法运行结束,此线程终止。然后CPU再调度其它线程。 2.run()方法当作普通方法 of方式调用。程序还是要顺序执行,要等待run方法体执行完毕后,才可继续执行下面 of代码;程序中只有主线程——这一个线程,其程序执行路径还是只有一条,这样就没有达到写线程 of目 The.

Remember: multithreading is the time-sharing use of the CPU, macro to allow all threads to execute together , also called concurrency

6). What is the difference between CyclicBarrier and CountDownLatch in Java

CountDownLatch

CyclicBarrier

Subtractive counting method

Adding count method

Release all waiting threads when the calculation is 0

Release all waiting threads when the count reaches the specified value

计数 because of0时,无法重置

When the count reaches the specified value, the count is set to 0 and restarted.

Calling the countDown() method decreases the count by one, and calling the await() method only blocks, which has no effect on the count

调用await()方法计数加1,若加1后 of值不等于构造方法 of值,则线程阻塞

Not reusable

Reusable

7). What is the Java memory model?

The Java memory model specifies and guides the deterministic behavior of Java programs across memory architectures, CPUs, and operating systems. It is especially important in the case of multi-threading. The Java memory model provides guarantees that changes made by one thread can be visible to other threads, and that they occur in a prior relationship. This relationship defines some rules for programmers to think more clearly when programming concurrently. For example, having a relationship first ensures that.

  • 线程内 of代码能够按先后顺序执行,这被称 because of程序次序规则。
  • 对于同一个 lock up,一个解 lock up操作一定要发生在时间上后发生 of另一个 lock up定操作之前,也叫做管程 lock up定规则。
  • The previous pairvolatile The write operation of the lattervolatile of读操作之前,也叫volatile Variable rules.
  • Any operation within a thread must follow the start() call of that thread, also known as the thread start rule.
  • All operations of a thread will be thread termination rules before the thread terminates.
  • The termination of an object must be done after the construction of the object is complete, also known as the object termination rule.
  • transferability

8).Java中 ofvolatile 变量是什么

可见性,是指线程之间 of可见性,一个线程修改 of状态对另一个线程是可见 The.也就是一个线程修改 of结果。另一个线程马上就能看到。比如:用volatile修饰 of变量,就会具有可见性。volatile修饰 of变量不允许线程内部缓存 harmony重排序,即直接修改内存。所以对其他线程是可见 The.但是这里需要注意一个问题,volatile只能让被他修饰内容具有可见性,但不能保证它具有原子性。比如 volatile int a = 0;之后有一个操作 a++;这个变量a具有可见性,但是a++ 依然是一个非 atomic operation,也就是这个操作同样存在线程安全问题。

Java语言提供了一种稍弱 of同步机制,即volatile变量,用来确保将变量 of更新操作通知到其他线程。当把变量声明 because ofvolatile类型后,编译器与运行时都会注意到这个变量是共享 of,因此不会将该变量上 of操作与其他内存操作一起重排序。volatile变量不会被缓存在寄存器或者对其他处理器不可见 of地方,因此在读取volatile类型 of变量时总会返回最新写入 of值。在访问volatile变量时不会执行加 lock up操作,因此也就不会使执行线程阻塞,因此volatile变量是一种比sychronized关键字更轻量级 of同步机制。

当对非 volatile 变量进行读写 of时候,每个线程先从内存拷贝变量到CPU缓存中。如果计算机有多个CPU,每个线程可能在不同 ofCPU上被处理,这意味着每个线程可以拷贝到不同 of CPU cache 中。而声明变量是 volatile of,JVM 保证了每次读变量都从内存中读,跳过 CPU cache 这一步。

当一个变量定义 because of volatile 之后,将具备两种特性: This variable is guaranteed to be visible to all threads; Disable instruction reordering optimization. Variables with volatile modifier, after the assignment, perform an additional "load addl $0x0, (%esp)" operation, which is equivalent to a memory barrier (instruction reordering can not reorder the later instructions to the location before the memory barrier), only one CPU access to memory, no memory barrier; (what is instruction reordering: is the CPU used to allow multiple instructions to be distributed to each corresponding circuit unit in the order specified by the program for processing).

9).What is thread safety? Is Vector a thread-safe class?

如果你 of代码所在 of进程中有多个线程在同时运行,而这些线程可能会同时运行这段代码。如果每次运行结果 harmony单线程运行 of结果是一样 of,而且其他 of变量 of值也 harmony预期 of是一样 of,就是线程安全 The.一个线程安全 of计数器类 of同一个实例对象在被多个线程使用 of情况下也不会出现计算失误。很显然你可以将集合类分成两组,线程安全 harmony非线程安全 The.Vector 是用同步方法来实现线程安全 of, 而 harmony它相似 ofArrayList不是线程安全 The.

10). What is a race condition in Java? Give an example.

当某个计算正确性取决于多个线程 of交替执行时序时, 就会发生静态条件,即争取 of结果要取决于运气, 最常见 of静态条件就是"先检查后执行",通过一个可能失效 of观测结果来决定下一步 of动作.

For example:

classCounter { protectedlongcount =0; publicvoidadd(longvalue) { this.count =this.count + value; } }

观察线程A harmonyB交错执行会发生什么,两个线程分别加了2 harmony3到count变量上,两个线程执行结束后count变量 of值应该等于5。然而 thanks to两个线程是交叉执行 of,两个线程从内存中读出 of初始值都是0。然后各自加了2 harmony3,并分别写回内存。最终 of值并不是期望 of5,而是最后写回内存 of那个线程 of值,上面例子中最后写回内存 of是线程A,但实际中也可能是线程B。如果没有采用合适 of同步机制,线程间 of交叉执行情况就无法预料。 The add() method is a critical zone, which generates a race condition.

11).What happens when an exception occurs while a thread is running

所以这里存在两种情形: ① 如果该异常被捕获或抛出,则程序继续运行。 ② 如果异常没有被捕获该线程将会停止执行。 Thread.UncaughtExceptionHandler是用于处理未捕获异常造成线程突然中断情况 of一个内嵌接口。当一个未捕获异常将造成线程中断 of时候JVM会使用Thread.getUncaughtExceptionHandler()来查询线程 ofUncaughtExceptionHandler,并将线程 harmony异常作 because of参数传递给handler ofuncaughtException()方法进行处理。

12).How do you communicate between threads and how do you communicate between processes?

Communication between multiple threads: 1). shared variables; 2),wait, notify; 3) Lock/Condition mechanism; 4).Pipeline mechanism, create PipedOutputStream pos and PipedInputStream pis, match pos and pis, pos.connect(pis), assign pos to the message input thread and pis to the message acquisition thread, then you can realize the communication between the threads.

Pipe flow, while easy to use, has some drawbacks

1) Pipeline streams can only pass data between two threads

线程consumer1 harmonyconsumer2同时从pis中read数据,当线程producer往管道流中写入一段数据后,每一个时刻只有一个线程能获取到数据,并不是两个线程都能获取到producer发送来 of数据,因此一个管道流只能用于两个线程间 of通讯。不仅仅是管道流,其他IO方式都是一对一传输。

2) Pipeline streams can only achieve one-way sending, if you want two threads to communicate with each other, you need two pipeline streams .

Inter-process communication:

1) Pipe: A pipe can be used for communication between related processes, allowing communication between a process and another process with which it has a common ancestor. (2)命名管道(named pipe):命名管道克服了管道没有名字 of限制,因此,除具有管道所具有 of功能外,它还允许无亲缘关 系进程间 of通信。命名管道在文件系统中有对应 of文件名。命名管道通过命令mkfifo或系统调用mkfifo来创建。 (3) signal (Signal): signal is a more complex way of communication, used to notify the receiving process of a certain event, in addition to inter-process communication, the process can also send a signal to the process itself; linux in addition to support Unix early signal semantic function sigal, but also support the semantics of the signal function in line with Posix.1 standard sigaction (in fact, the function is based on BSD, BSD in order to achieve a reliable signal mechanism, but also to unify the external interface, with the sigaction function re-implementation of the signal function). (4) Message (Message) queue: Message queue is a link table of messages, including Posix message queue system V message queue. Processes with sufficient privileges can add messages to the queue, and processes given read privileges can read away the messages in the queue. The message queue overcomes the shortcomings of low signal-carrying information, pipelines that can only carry unformatted byte streams, and limited buffer sizes (5) Shared memory: enables multiple processes to access the same memory space and is the fastest form of available IPC. is designed for other communication mechanisms that operate less efficiently. It is often used in combination with other communication mechanisms, such as semaphores, to achieve synchronization and mutual exclusion between processes. (6) memory mapping (mapped memory): memory mapping allows any multiple processes to communicate with each other, and each process that uses this mechanism does it by mapping a shared file to its own process address space. (7) semaphore: mainly as a means of synchronization between processes and between different threads of the same process.

(8) Socket: A more general inter-process communication mechanism that can be used for inter-process communication between different machines. Originally developed by the BSD branch of Unix systems, but now generally portable to other Unix-like systems: Linux and variants of System V both support sockets.

13). What is the difference between notify and notifyAll in Java?

notify()&notifyall() of共同点:均能唤醒正在等待 of线程,并且均是最后只有一个线程获取资源对象 of lock up。

不同点:notify() 只能唤醒一个线程,而notifyall()能够唤醒所有 of线程,当线程被唤醒以后所有被唤醒 of线程竞争获取资源对象 of lock up,其中只有一个能够得到对象 lock up,执行代码。

注意:wait()方法并不是在等待资源 of lock up,而是在等待被唤醒(notify()),一旦被唤醒后,被唤醒 of线程就具备了资源 lock up(因 because of无需竞争),直至再次执行wait()方法或者synchronized代码块执行完毕。

14).Why are the wait, notify and notifyAll methods not in the thread class?

One obvious reason is that JAVA provides locks at the object level rather than the thread level, and each object has a lock, obtained through the thread. If the thread needs to wait for some lock then it makes sense to call the wait() method in the object. If the wait() method is defined in the Thread class, it's not obvious which lock the thread is waiting for. Simply put, since wait, notify and notifyAll are all lock-level operations, they are defined in the Object class because locks belong to objects.

15).What is a ThreadLocal variable?

ThreadLocal is generally referred to as thread-local variables.它是一种特殊 of线程 bind机制,将变量与线程 bind在一起, because of每一个线程维护一个独立 of变量副本。通过ThreadLocal可以将对象 of可见范围限制在同一个线程内。

jump out of the box

  The important thing to emphasize is not to make analogies between ThreadLocal and synchronized, because such comparisons are simply meaningless! sysnchronized is a mutually exclusive synchronization mechanism that is designed to ensure proper access to shared resources in a multi-threaded environment. And ThreadLocal, by its very nature, does nothing more than provide a "Thread Level" of variable scope , it is a Thread Closure(每个线程独享变量)技术,更直白点讲,ThreadLocal可以理解 because of将对象 of作用范围限制在一个 Thread Context中,使得变量 of作用域 because of“ thread-level”。

  Without ThreadLocal, a thread may pass through multiple levels and methods during its declaration cycle, and if there is an object that needs to be called multiple times during the thread cycle and is shared across levels (within threads), the usual practice is to pass it through parameters; ThreadLocal binds variables to threads, and objects can be easily retrieved through the get method it provides during a thread cycle, no matter "where you are". Greatly improves the ease of access to "thread-level variables".

16).Java中ThreadLocal变量, volatile变量, synchronized of区别

volatile主要是用来在多线程中同步变量。 在一般情况下, because of了提升 performance,每个线程在运行时都会将主内存中 of变量保存一份在自己 of内存中作 because of变量副本,但是这样就很容易出现多个线程中保存 of副本变量不一致,或与主内存 of中 of变量值不一致 of情况。 而当一个变量被volatile修饰后,该变量就不能被缓存到线程 of内存中,它会告诉编译器不要进行任何移出读取 harmony写入操作 of优化,换句话说就是不允许有不同于“主”内存区域 of变量拷贝,所以当该变量有变化时,所有调用该变量 of线程都会获得相同 of值,这就确保了该变量在应用中 of可视性(当一个任务做出了修改在应用中必须是可视 of),同时 performance也相应 of降低了(还是比synchronized高)。 但需要注意volatile只能确保操作 of是同一块内存,并不能保证操作 of原子性。所以volatile一般用于声明简单类型变量,使得这些变量具有原子性,即一些简单 of赋值与返回操作将被确保不中断。但是当该变量 of值由自身 of上一个决定时,volatile of作用就将失效,这是由volatile关键字 of性质所决定 The. 所以在volatile时一定要谨慎,千万不要以 because of用volatile修饰后该变量 of所有操作都是 atomic operation,不再需要synchronized关键字了。

ThreadLocal是一个线程 of局部变量(其实就是一个Map),ThreadLocal会 because of每个使用该变量 of线程提供独立 of变量副本,所以每一个线程都可以独立地改变自己 of副本,而不会影响其它线程所对应 of副本。这样做其实就是以空间换时间 of方式(与synchronized相反),以耗费内存 because of代价,单大大减少了线程同步(如synchronized)所带来 performance消耗以及减少了线程并发控制 of复杂度。

synchronized关键字是Java利用 lock up of机制自动实现 of,一般有同步方法 harmony同步代码块两种使用方式。Java中所有 of对象都自动含有单一 of lock up(也称 because of监视器),当在对象上调用其任意 ofsynchronized方法时,此对象被加 lock up(一个任务可以多次获得对象 of lock up,计数会递增),同时在线程从该方法返回之前,该对象内其他所有要调用类中被标记 because ofsynchronized of方法 of线程都会被阻塞。

17).What is Future, FutureTask?

 Future就是对于具体 ofRunnable或者Callable任务 of执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。

   The Future class is located under the java.util.concurrent package and it is an interface to.

publicinterfaceFuture<V> {
booleancancel(booleanmayInterruptIfRunning);
booleanisCancelled();
booleanisDone();
V get()throwsInterruptedException, ExecutionException;
V get(longtimeout, TimeUnit unit)
throwsInterruptedException, ExecutionException, TimeoutException;
}

  在Future接口中声明了5个方法,下面依次解释每个方法 of作用:

  • cancel方法用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。参数mayInterruptIfRunning表示是否允许取消正在执行却没有执行完毕 of任务,如果设置true,则表示可以取消正在执行过程中 of任务。如果任务已经完成,则无论mayInterruptIfRunning because oftrue还是false,此方法肯定返回false,即如果取消已经完成 of任务会返回false;如果任务正在执行,若mayInterruptIfRunning设置 because oftrue,则返回true,若mayInterruptIfRunning设置 because offalse,则返回false;如果任务还没有执行,则无论mayInterruptIfRunning because oftrue还是false,肯定返回true。
  • The isCancelled method indicates whether the task was cancelled successfully or not, and returns true if it was cancelled successfully before the task completed normally.
  • the isDone method indicates whether the task has completed, and returns true if the task is complete.
  • (a) The get() method is used to obtain the result of execution; this method generates blocking and will wait until the task has been executed before returning.
  • get(long timeout, TimeUnit unit) is used to get the result of the execution, if within the specified time, the result has not been fetched, it will return null directly.

   This means that Future offers three functions.

   1) To determine whether the task is complete.

   (2) The ability to interrupt tasks.

   3) Ability to obtain results of task execution.

publicclassFutureTask<V>implementsRunnableFuture<V>

FutureTask类实现了RunnableFuture接口,我们看一下RunnableFuture接口 of实现:

publicinterfaceRunnableFuture<V>extendsRunnable, Future<V> {
voidrun();
}

在Java并发程序中FutureTask表示一个可以取消 of异步运算。它有启动 harmony取消运算、查询运算是否完成 harmony取回运算结果等 Methods.只有当运算完成 of时候结果才能取回,如果运算尚未完成get方法将会阻塞。一个FutureTask对象可以对调用了Callable harmonyRunnable of对象进行包装, thanks toFutureTask也是调用了Runnable接口所以它可以提交给Executor来执行。

18).Java中interrupted harmony isInterruptedd方法 of区别?

interrupted() harmonyisInterrupted() The main difference is that the former will clear the interrupt state while the latter will not. The Java multithreaded interrupt mechanism is implemented with internal markers, callingThread.interrupt()来中断一个线程就会设置中断标识 because oftrue。当中断线程调用 Static methodsThread.interrupted() to check the interrupt status, the interrupt status will be cleared to zero. The non-static method isInterrupted() is used to query the interrupt status of other threads and does not change the interrupt status identifier. The simple fact is that any method that throws an InterruptedException exception will zero out the interrupted state. In any case, it is possible for a thread's interrupt state to be changed by other threads calling interrupts.

interrupt方法是用于中断线程 of,调用该方法 of线程 of状态将被置 because of"中断"状态。注意:线程中断仅仅是设置线程 of中断状态位,不会停止线程。需要用户自己去监视线程 of状态 because of并做处理。支持线程中断 of方法(也就是线程中断后会抛出InterruptedException of方法,比如这里 ofsleep,以及Object.wait等方法)就是在监视线程 of中断状态,一旦线程 of中断状态被置 because of“中断状态”,就会抛出中断异常。

interrupted方法 of实现:

  1. publicstaticbooleaninterrupted(){
  2. returncurrentThread().isInterrupted(true);
  3. }

and isInterrupted implementations

  1. publicbooleanisInterrupted(){
  2. returnisInterrupted(false);
  3. }

One of these two methods is static and one is not, but both are actually calling the same method, except that the interrupted method is passed with a true argument and the inInterrupted is passed with a false argument. This is a native method, it doesn't matter if you can't see the source code, the parameter name ClearInterrupted already clearly expresses the role of the parameter ---- whether to clear the interrupted state. The annotation of the method also clearly states that "the interrupted state will be reset or not depending on the value of the ClearInterrupted parameter passed in". So, the static method interrupted will clear the interrupted state (the passed parameter ClearInterrupted is true), while the instance method isInterrupted will not (the passed parameter ClearInterrupted is false).

19). Volatile and atomic classes in Java?

If a variable has the volatile keyword added, it tells the compiler and the JVM's memory model that the variable is shared and visible to all threads, and that each time jvm reads the most recently written value and makes its latest value visible to all CPUs. It seems that volatile is sometimes a good substitute for a simple lock, and it seems that adding the volatile keyword eliminates the lock. But then it says that volatile does not guarantee atomicity (java programmers are familiar with this phrase: volatile is only used to guarantee the visibility of that variable to all threads, but not atomicity). If your field is volatile, the Java memory model will insert a write barrier instruction after a write operation and a read barrier instruction before a read operation. This means that if you do a write operation to a volatile field, you must know that 1. Once you finish writing, any threads that access the field will get the latest value. 2, before you write, will ensure that everything that has happened before has happened and that any updated data values are also visible, as the memory barrier will flush all previous write values to the cache.

volatile because of什么没有原子性?

Understanding the memory barrier (memory barrier)这个CPU指令,回到前面 ofJVM指令:从Load到store到内存屏障,一共4步,其中最后一步jvm让这个最新 of变量 of值在所有线程可见,也就是最后一步让所有 ofCPU内核都获得了最新 of值,但中间 of几步(从Load到Store)是不安全 of,中间如果其他 ofCPU修改了值将会丢失。

原子类保证了解决了上述 ofvolatile of原子性没有保证 of问题, 用到了CAS操作,

因 because ofCAS是基于乐观 lock up of,也就是说当写入 of时候,如果寄存器旧值已经不等于现值,说明有其他CPU在修改,那就继续尝试。所以这就保证了操作 of原子性。

19).Why wait and notify methods are called in a synchronization block?

Mainly because the Java API forces this, and if you don't, your code will throw an IllegalMonitorStateException. Another reason is to avoid a race condition between wait and notify.

20).Java中 of同步集合与并发集合有什么区别

Synchronized vs Concurrent Collections

不管是同步集合还是并发集合他们都支持线程安全,他们之间主要 of区别体现在 performance harmony scalability,还有他们如何实现 of线程安全。同步HashMap, Hashtable, HashSet, Vector, ArrayList 相比他们并发 of实现(比如:ConcurrentHashMap, CopyOnWriteArrayList, CopyOnWriteHashSet)会慢得多。造成如此慢 of主要原因是 lock up , a synchronous collection locks the entire Map or List, while a concurrent collection does not. Concurrent collections achieve thread safety by using advanced and proven techniques like lock stripping. For example, ConcurrentHashMap divides the entire Map into segments and locks only the relevant segments, while allowing multiple threads to access other unlocked segments.

同样 of,CopyOnWriteArrayList 允许多个线程以非同步 of方式读,当有线程写 of时候它会将整个List复制一个副本给它。

如果在读多写少这种对并发集合有利 of条件下使用并发集合,这会比使用同步集合更具有可伸缩性。

同步集合与并发集合都 because of多线程 harmony并发提供了合适 of线程安全 of集合,不过并发集合 of scalability更高。在Java1.5之前程序员们只有同步集合来用且在多线程并发 of时候会导致争用,阻碍了系统 of扩展性。Java5介绍了并发集合像ConcurrentHashMap,不仅提供线程安全还用 lock up分离 harmony内部分区等现代技术提高了 scalability。

21). What is the difference between heap and stack in Java?

因 because of栈是一块 harmony线程紧密相关 of内存区域。每个线程都有自己 of栈内存,用于存储本地变量,方法参数 harmony栈调用,一个线程中存储 of变量对其它线程是不可见 The.而堆是所有线程共享 of一片公用内存区域。对象都在堆里创建, because of了提升效率线程会从堆中弄一个缓存到自己 of栈,如果多个线程使用该变量就可能引发问题,这时volatile 变量就可以发挥作用了,它要求线程从主存中读取变量 of值。

22).What is a thread pool? Why should I use it?

创建线程要花费昂贵 of资源 harmony时间,如果任务来了才创建线程那么响应时间会变长,而且一个进程能创建 of线程数有限。 because of了避免这些问题,在程序启动 of时候就创建若干线程来响应处理,它们被称 because of线程池,里面 of线程叫工作线程。从JDK1.5开始,Java API提供了Executor框架让你可以创建不同 of线程池。比如单线程池,每次处理一个任务;数目固定 of线程池或者是缓存线程池(一个适合很多生存期短 of任务 of程序 of可扩展线程池)。

22).实现 manufacturer consumers模式

package ProducterAndConsumer.Version1;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *  manufacturer

 *  manufacturer consumers模型
 */

public class Producer implements Runnable {
    private volatile boolean isRunning = true;
    private BlockingQueue<PCData> queue;//  memory buffer
    private static AtomicInteger count = new AtomicInteger();//  totals  atomic operation
    private static final int SLEEPTIME = 1000;

    public Producer(BlockingQueue<PCData> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        PCData data = null;
        Random r = new Random();
        System.out.println("start producting id:" + Thread.currentThread().getId());
        try {
            while (isRunning) {
                Thread.sleep(r.nextInt(SLEEPTIME));
                data = new PCData(count.incrementAndGet());
                System.out.println(data + "  Join the queue");
                if (!queue.offer(data, 2, TimeUnit.SECONDS)) {
                    System.err.println("  Failed to join the queue");
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }

    }

    public void stop() {
        isRunning = false;
    }
}
package ProducterAndConsumer.Version1;
/**
 *  consumers
 * 
 */
import java.text.MessageFormat;
import java.util.Random;
import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable{
    private BlockingQueue<PCData> queue;
    private static final int SLEEPTIME = 1000;
    public Consumer(BlockingQueue<PCData> queue){
        this.queue = queue;
    }

    @Override
    public void run() {
        System.out.println("start Consumer id :"+Thread.currentThread().getId());
        Random r = new Random();
        try{
            while(true){
                PCData data = queue.take();
                if(data != null)
                {
                    int re = data.getData() * data.getData();
                    System.out.println(MessageFormat.format("{0}*{1}={2}", data.getData(),data.getData(),re));
                    Thread.sleep(r.nextInt(SLEEPTIME));
                }
            }
        }catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

}
package ProducterAndConsumer.Version1;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

/**
 *  principal function
 * @author ctk
 *
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<PCData> queue = new LinkedBlockingDeque<>(10);
        Producer p1 = new Producer(queue);
        Producer p2 = new Producer(queue);
        Producer p3 = new Producer(queue);
        Consumer c1 = new Consumer(queue);
        Consumer c2 = new Consumer(queue);
        Consumer c3 = new Consumer(queue);
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(p1);
        service.execute(p2);
        service.execute(p3);
        service.execute(c1);
        service.execute(c2);
        service.execute(c3);
        Thread.sleep(10*1000);
        p1.stop();
        p2.stop();
        p3.stop();
        Thread.sleep(3000);
        service.shutdown();
    }
}
package ProducterAndConsumer.Version1;
/**
 *  Container data type
 * @author ctk
 *
 */
public class PCData {
    private final int intData;
    public PCData(int d){
        intData = d;
    }
    public PCData(String d){
        intData = Integer.valueOf(d);
    }
    public int getData(){
        return intData;
    }
    @Override
    public String toString(){
        return "data:"+intData;
    }
}

23).How to avoid deadlock?

Java多线程中 of死 lock up 死 lock up是指两个或两个以上 of进程在执行过程中,因争夺资源而造成 of一种互相等待 of现象,若无外力作用,它们都将无法推进下去。这是一个严重 of问题,因 because of死 lock up会让你 of程序挂起无法完成任务,死 lock up of发生必须满足以下四个条件:

  • Mutual exclusion condition: a resource can only be used by one process at a time.
  • Request and hold condition: when a process blocks due to a request for a resource, it holds on to the acquired resource.
  • 不剥夺条件:进程已获得 of资源,在末使用完之前,不能强行剥夺。
  • Cyclic wait condition: a head-to-tail cyclic wait resource relationship is formed between several processes.

避免死 lock up最简单 of方法就是阻止循环等待条件,将系统中所有 of资源设置标志位、排序,规定所有 of进程申请资源必须以一定 of顺序(升序或降序)做操作来避免死 lock up。

24).Java中活 lock up harmony死 lock up有什么区别?

A live lock is similar to a deadlock, with the difference that the state of the thread or process in a live lock is constantly changing, and a live lock can be thought of as a special kind of starvation. A real life example of a live lock is when two people run into each other in a narrow hallway and both try to avoid each other so they can get through, but because the avoidance is in the same direction neither one ends up getting through the hallway. Simply put, the main difference between a live lock and a deadlock is that the state of the former process can be changed but execution cannot continue.

25)怎么检测一个线程是否拥有 lock up?

There is a method in java.lang.Thread called holdsLock() which returns true if and only if the current thread has a lock on a specific object.

26).JVM中哪个参数是用来控制线程 of栈堆栈小 of

-The Xss parameter is used to control the size of the thread's stack.

27). What is the difference between synchronized and ReentrantLock in Java?

Similarities.

这两种同步方式有很多相似之处,它们都是加 lock up方式同步,而且都是阻塞式 of同步,也就是说当如果一个线程获得了对象 lock up,进入了同步块,其他访问该同步块 of线程都必须阻塞在同步块外面等待,而进行线程阻塞 harmony唤醒 of代价是比较高 of(操作系统需要在用户态与内核态之间来回切换,代价很高,不过可以通过对 lock up优化进行改善)。

Distinction.

这两种方式最大区别就是对于Synchronized来说,它是java语言 of关键字,是原生语法层面 of互斥,需要jvm实现。而ReentrantLock它是JDK 1.5之后提供 ofAPI层面 of互斥 lock up,需要lock() harmonyunlock()方法配合try/finally语句块来完成。

Synchronized进过编译,会在同步块 of前后分别形成monitorenter harmonymonitorexit这个两个字节码指令。在执行monitorenter指令时,首先要尝试获取对象 lock up。如果这个对象没被 lock up定 , or当前线程已经拥有了那个对象 lock up,把 lock up of计算器加1,相应 of,在执行monitorexit指令时会将 lock up计算器就减1,当计算器 because of0时, lock up就被释放了。如果获取对象 lock up失败,那当前线程就要阻塞,直到对象 lock up被另一个线程释放 because of止。

Since ReentrantLock is a set of mutually exclusive locks provided under the java.util.concurrent package, the ReentrantLock class provides some advanced features compared to Synchronized, mainly the following 3.

1.等待可中断,持有 lock up of线程长期不释放 of时候,正在等待 of线程可以选择放弃等待,这相当于Synchronized来说可以避免出现死 lock up of情况。

2.公平 lock up,多个线程等待同一个 lock up时,必须按照申请 lock up of时间顺序获得 lock up,Synchronized lock up非公平 lock up,ReentrantLock默认 of构造函数是创建 of非公平 lock up,可以通过参数true设 because of公平 lock up,但公平 lock up表现 of performance不是很好。

3. lock up bind多个条件,一个ReentrantLock对象可以同时 bind对个对象。

28).There are three threads T1, T2, T3, how do you ensure that they execute in order?

There are several ways to have threads execute in a specific order in multithreading, and you can use the join() method of the thread class to start another thread in one thread, and another thread to finish that thread to continue execution. To make sure the three threads are in order you should start the last one first (T3 calls T2, T2 calls T1) so that T1 finishes first and T3 finishes last.

29).Thread类中 ofyield方法有什么作用?

The yield() method can suspend the currently executing thread, but it will not block the thread It's just... Transferring the thread from running to ready state

只是让当前 of线程暂停一下,让系统 of线程调度器重新调度一次。

很有可能,当某个线程调用了yield()方法暂停之后进入就绪状态,它又马上抢占了CPU of执行权,继续执行。

In fact, after a thread has called the yield() method to pause, only Priority is the same as the current thread , or Higher priority than the current thread of处于就绪状态 of线程才会获得执行 of机会。

[On the difference between sleep and yield]

1.After the sleep() method suspends the current thread, it gives other threads a chance to execute, and thread priority has no effect on this.

yield()方法会给优先级相同或更高 of线程更高 of执行机会。

2.The sleep() method will shift the thread into a blocking state until the blocking time is over, then it will move to the ready state.

The yield() method will move the current thread directly into the ready state.

3.The sleep() method declaration throws an InterruptedException exception, so calls to the sleep() method either catch the exception or show the declaration throwing the exception.

The yield() method, on the other hand, does not declare any exceptions to be thrown.

4.sleep()方法比yield()方法有更好 of移植性,通常不建议使用yield()方法来控制并发线程 of执行.

30). What is Semaphore in Java?

Semaphore in Java is a new synchronization class that is a counting signal. Conceptually, conceptually, semaphores maintain a collection of permissions. If necessary, each acquire() will be blocked until the permit is available, and then the permit will be acquired. Each release() adds a permit so that a blocking getter may be released. However, instead of using the actual license object, Semaphore only counts the number of available licenses and takes action accordingly. Semaphores are often used in multi-threaded code, such as database connection pools.

31). if the thread pool queue is full when you submit the task. What will be born when the hair will be?

If a task cannot be scheduled for execution then ThreadPoolExecutor's submit() method will throw a RejectedExecutionException.

32). What is the difference between submit() and execute() methods in Java thread pool?

1.Different handling of return values The execute method does not care about the return value. The submit method has a return value, Future. 2.Different handling of exceptions The excute method will throw an exception. The sumbit method does not throw an exception. Unless you call Future.get()

33).What is a blocking method?

阻塞式方法是指程序会一直等待该方法完成期间不做其他事情,ServerSocket ofaccept()方法就是一直等待客户端连接。这里 of阻塞是指调用结果返回之前,当前线程会被挂起,直到得到结果之后才会返回。此外,还有异步 harmony非阻塞式方法在任务完成前就返回。

34) Is Swing thread-safe? Why?

Swing不是线程安全 of,但是你应该解释这么回答 of原因即便面试官没有问你 because of什么。当我们说swing不是线程安全 of常常提到它 of组件,这些组件不能在多线程中进行修改,所有对GUI组件 of更新都要在AWT线程中完成,而Swing提供了同步 harmony异步两种回调方法来进行更新。

35). What is the difference between invokeAndWait and invokeLater in Java?

invokeAndWait:后面 of程序必须等这个线程(参数中 of线程) of东西执行完才能执行 invokeLater:后面 of程序 harmony这个参数 of线程对象可以并行,异步地执行

invokeLater一般用于在线程里修改swing组件 of外观,因 because ofswing组件 right and wrong同步 of,所以不能在线程中直接修改,会不同步,得不到期望 of效果,所以要把修改外观 of代码放在一个单独 of线程中,交给invokeLater:后面 of程序 harmony这个参数 of线程对象可以并行,异步地执行.

36).Swing API中那些方法是线程安全 of?

这个问题又提到了swing harmony线程安全,虽然组件不是线程安全 of但是有一些方法是可以被多线程安全调用 of,比如repaint(), revalidate()。 JTextComponent ofsetText()方法 harmonyJTextArea ofinsert() harmony append() 方法也是线程安全 The.

37).How to create Immutable(immutable) objects in Java?

Immutable对象可以在没有同步 of情况下共享,降低了对该对象进行并发访问时 of同步化开销。可是Java没有@Immutable这个注解符,要创建不可变类,要实现下面几个步骤:通过构造方法初始化所有成员、对变量不要提供setter方法、将所有 of成员声明 because of私有 of,这样就不允许直接访问这些成员、在getter方法中,不要直接返回对象本身,而是克隆对象,并返回对象 of拷贝。

38).Java中 ofReadWriteLock是什么?

ReadWriteLock in Java is a new interface in Java 5. A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writes. In the absence of a write thread a read lock may be held by multiple read threads at the same time. Write locks are exclusive, and you can implement this rule using ReentrantReadWriteLock in the JDK, which supports up to 65535 write locks and 65535 read locks.

39).多线程中 of忙循环是什么?

A busy loop is when a programmer uses a loop to make a thread wait, unlike the traditional methods wait(), sleep() or yield() which give up CPU control, a busy loop does not give up CPU, it just runs an empty loop. The purpose of doing this is to preserve the CPU cache, which in a multicore system may be running on another core when a waiting thread wakes up, which will rebuild the cache. To avoid rebuilding the cache and to reduce the time spent waiting for a rebuild it can be used.

40).如果同步块内 of线程抛出异常会发生什么?

Whether your synchronization block exits normally or abnormally, the threads inside will release the lock.

41).What is the double check lock for the singleton pattern?

public static Singleton getInstance()
{
  if (instance == null)
  {
    synchronized(Singleton.class) {  //1
      if (instance == null)          //2
        instance = new Singleton();  //3
    }
  }
  return instance;
}

双重检查 lock up定背后 of理论是:在 //2 处 of第二次检查使(如清单 3 中那样)创建两个不同 ofSingleton The object becomes impossible. Assume the following sequence of events.

  1. Thread 1 EntergetInstance() Methods.
  2. thanks toinstance because ofnull , thread 1 enters at //1synchronized Block.
  3. Thread 1 is preoccupied by thread 2.
  4. Thread 2 EntergetInstance() Methods.
  5. thanks toinstance remain asnull Thread 2 tries to get the lock at //1. However, because thread 1 holds the lock, thread 2 blocks at //1.
  6. Thread 2 is preoccupied by thread 1.
  7. 线程 1 执行, thanks to在 //2 处实例 remain asnull , thread 1 also creates aSingleton object and assigning its reference to theinstance
  8. Thread 1 Exitsynchronized block and fromgetInstance() method returns the instance.
  9. Thread 1 is preoccupied by thread 2.
  10. 线程 2 获取 //1 处 of lock up并检查instance是否 because ofnull
  11. thanks toinstance right and wrongnull of,并没有创建第二个Singleton object, created by thread 1, is returned.

双重检查 lock up定背后 of理论是完美 The.不幸地是,现实完全不同。双重检查 lock up定 of问题是:并不能保证它会在单处理器或多处理器计算机上顺利运行。

双重检查 lock up定失败 of问题并不归咎于 JVM 中 of实现 bug,而是归咎于 Java 平台内存模型。内存模型允许所谓 of“ disorderly writing”,这也是这些习语失败 of一个主要原因。

disorderly writing

To explain this, the //3 line in Listing 4 above needs to be revisited. This line of code creates aSingleton object and initialize the variableinstance to reference this object. The problem with this line of code is that theSingleton Before the constructor body is executed, the variableinstance May become a non-null The.

42).写出3条你遵循 of多线程最佳实践

This kind of question is my favorite, and I'm sure you follow certain best practices when writing concurrent code to improve performance. Here are three best practices that I think most Java programmers should follow.

  • 给你 of线程起个有意义 of名字。 这样可以方便找bug或追踪。OrderProcessor, QuoteProcessor or TradeProcessor 这种名字比 Thread-1. Thread-2 and Thread-3 好多了,给线程起一个 harmony它要完成 of任务相关 of名字,所有 of主要框架甚至JDK都遵循这个最佳实践。
  • 避免 lock up定 harmony缩小同步 of范围 lock up花费 of代价高昂且上下文切换更耗费时间空间,试试最低限度 of使用同步 harmony lock up,缩小临界区。因此相对于同步方法我更喜欢同步块,它给我拥有对 lock up of绝对控制权。
  • Use more synchronous classes and less wait and notify First, the synchronization classes CountDownLatch, Semaphore, CyclicBarrier and Exchanger simplify coding operations that are difficult to achieve with wait and notify for complex control flows. Secondly, these classes are written and maintained by the best companies in the business and they will continue to be optimized and improved in subsequent JDKs, and your programs can be optimized without much effort using these higher level synchronization tools.
  • Use more concurrent collections and less synchronous collections This is another best practice that is easy to follow and benefits tremendously; concurrent collections are more scalable than synchronous collections, so using concurrent collections works better when programming concurrently. If you need to use a map the next time, you should think of using ConcurrentHashMap first.

43).Java中 offork join框架是什么?

fork join框架是JDK7中出现 of一款高效 of工具,Java开发人员可以通过它充分利用现代服务器上 of多处理器。它是专门 because of了那些可以递归划分成许多子模块设计 of,目 of是将所有可用 of处理能力用来提升程序 of performance。fork join框架一个巨大 of优势是它使用了工作窃取算法,可以完成更多任务 of工作线程可以从其它线程中窃取任务来执行。

44). What is the difference between calling wait() and sleep() methods in Java multithreading?

Java程序中wait harmony sleep都会造成某种形式 of暂停,它们可以满足不同 of需要。wait()方法用于线程间通信,如果等待条件 because of真且其它线程被唤醒时它会释放 lock up,而sleep()方法仅仅释放CPU资源或者让当前线程停止执行一段时间,但不会释放 lock up。


Recommended>>
1、Vulnerability Alert Wellknown WordPress themes Pagelines and Platform are highly vulnerable
2、210VR Scan new Valve patent could greatly reduce the gauze effect on VR headsets SceneCam camera gets 12m investment
3、python generator
4、Into Interaction Design Experience interaction design in life
5、Controlling referrers with the RefererMeta tag detailing referrerpolicy

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    Contact US

    Welcome to Intefrankly.

    Intefrankly is a platform that you can show your opnions related to IT technology, and communicates to the people who interested in IT and Artificial Intelligence area.