A summary of multi-thread threads

Source: Internet
Author: User
Tags thread class volatile

What is atomic manipulation? What are the atomic manipulation classes in the Java Concurrency API?

Atomic operation is the operation of a single task unit, this operation does not need to interfere with other operations, it can be understood as the current situation is non-sub-operation, far from the operation is a multi-threaded environment to avoid inconsistent data and the existence of necessities.

Int++ is not an atomic operation, if one thread reads its value in parallel with +1 operations, while another thread reads the old value, it results in an incorrect result.

To solve this problem, we need to make sure that the increment operation is atomic, you can use synchronous primitives (synchronization), or you can use the Java5 wrapper to AtomicInteger complete the atomic operation directly. Classes that java.util.concurrent.atomic begin with a atomic at the bottom of a package are atomic classes. For example AtomicInteger , AtomicReference wait for

What is Java Cuncurrency APIMiddle Lock interface? Relative to Synchronization ( synchronizationWhat are the advantages?

First we look at the definition of the lock interface:

Lock is a tool class that controls multi-threaded access to shared resources, is more extensible than using the Synchronized method or statement, has a flexible structure, can have completely different properties, and can support conditional objects of multiple related classes. Here's how to use it:

  {@code   Lock l = ...;   l.lock();   try {   // 访问锁保护的共享资源    } finally {   l.unlock();  }}
    • With respect to synchronization, there are the following advantages:
    • Can make the lock more fair
    • Allows threads to respond to interrupts while waiting for a lock
    • Allows a thread to attempt to acquire a lock and return immediately or wait for a period of time when the lock cannot be acquired
    • Locks can be acquired and freed in different scopes and in various order
What is the executors framework?

In Java5, the executor framework java.util.concurrent.Executor is introduced along with the interface, and the executor framework standardizes thread invocation, scheduling, execution, and control of asynchronous tasks.
Uncontrolled thread creation can cause memory overflow, and a thread pool (ThreadPool) that creates a finite number of threads is a good choice, and threads can be pre-created, recycled, and reused. The executor framework facilitates the creation of the Java thread pool, with the following sample code:

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class SimpleThreadPool {    public static void main(String[] args) {        ExecutorService executor = Executors.newFixedThreadPool(5);        for (int i = 0; i < 10; i++) {            Runnable worker = new WorkerThread("" + i);            executor.execute(worker);          }        executor.shutdown();        while (!executor.isTerminated()) {        }        System.out.println("Finished all threads");    }}
What is a blocking queue (blockingqueue)? How do I use a blocking queue to implement producer-consumer issues?

Blockingqueue is a blocking queue, as the name implies, when retrieving and deleting, if the queue is empty, then block wait until the queue is not empty, when adding elements to the queue, if no space will block waiting until the queue has space. The interface definition is as follows:

Blockingqueue does not accept null values and throws a null pointer exception if the store is null. Blocingqueue implementations are thread-safe, using internal locks or other concurrency control methods.

The common methods of Blockingqueue definition are as follows:

    • Add (AnObject): Adds anobject to Blockingqueue, returns true if Blockingqueue can accommodate, otherwise throws an exception.
    • Offer (AnObject): Indicates that if possible, AnObject is added to Blockingqueue, that is, true if blockingqueue can accommodate, otherwise false is returned.
    • Put (anobject): Add AnObject to Blockingqueue, and if Blockingqueue has no space, the thread calling this method is blocked until there is space in the blockingqueue to continue.
    • Poll (time): Take the object in the first place in the Blockingqueue, if not immediately remove, you can wait for the times specified in the parameters, and return NULL when not taken.
    • Take (): Takes the Blockingqueue in the first place of the object, if the blockingqueue is empty, blocking into the waiting state until Blockingqueue a new object is added.

Blockingqueue has four specific implementation classes, depending on the requirements, choose different implementation classes:

    • Arrayblockingqueue: The blockingqueue of the specified size, whose constructor must take an int parameter to indicate its size. The objects it contains are sorted in FIFO (first in, first out) order.
    • Linkedblockingqueue: Blockingqueue of variable size, if its constructor takes a specified size parameter, the resulting blockingqueue has a size limit, without the size parameter, The size of the generated blockingqueue is determined by Integer.max_value. The objects it contains are sorted in FIFO order.
    • Priorityblockingqueue: Similar to Linkedblockingqueue, but the sort of objects it contains is not FIFO, but is based on the object's natural sort order or the order in which the comparator is determined by the constructor.
    • Synchronousqueue: Special Blockingqueue, the operation of which must be put and take the alternate completion.

LinkedBlockingQueueIn ArrayBlockingQueue comparison, the data structure behind them is different, resulting in linkedblockingqueue data throughput greater than Arrayblockingqueue, However, when the number of threads is large, its performance is less predictable than arrayblockingqueue.
Implement producer-consumer code as follows: Message.java

public class Message {    private String msg ;    public String getMsg() {        return msg;    }    public void setMsg(final String msg) {        this.msg = msg;    }    public Message(final String msg) {        this.msg = msg;    }}

Producer.java

import java.util.concurrent.BlockingQueue;public class Producer implements Runnable {    private BlockingQueue<Message> messageBlockingDeque;    public Producer(final BlockingQueue<Message> messageBlockingDeque) {        this.messageBlockingDeque = messageBlockingDeque;    }    @Override    public void run() {        for (int i = 0; i <100 ; i++) {           Message msg = new Message(" "+i);            try {                Thread.sleep(i);                messageBlockingDeque.put(msg);                System.out.println("Produced:"+msg.getMsg());            } catch (InterruptedException e) {                e.printStackTrace();            }        }        Message msg = new Message("exit");        try {            messageBlockingDeque.put(msg);        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

Consumer.java

public class Consumer implements Runnable {    private BlockingQueue<Message> blockingDeque;    public Consumer(final BlockingQueue<Message> blockingDeque) {        this.blockingDeque = blockingDeque;    }    @Override    public void run() {         Message message;        try {            while((message= blockingDeque.take()).getMsg()!="exit"){                Thread.sleep(10);                System.out.println("Consumed:"+message.getMsg());            }        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

Productconsumerservice.java

public class ProductConsumerService {    public static void main(String[] args) {        BlockingQueue<Message> queue = new ArrayBlockingQueue<Message>(10);        Producer producer = new Producer(queue);        Consumer consumer = new Consumer((queue));        ExecutorService executorService = Executors.newCachedThreadPool();        executorService.submit(producer);        executorService.submit(consumer);        try {            Thread.sleep(10000);        } catch (InterruptedException e) {            e.printStackTrace();        }        executorService.shutdown();    }}
What is callable and future?

Java 5 introduces the Java.util.concurrent.Callable interface in the concurrency package, which is similar to the Runnable interface, but it can return any object or throw an exception.

The

Callable interface uses generics to define its return type. The Executors class provides some useful ways to perform tasks within a callable in a thread pool. Since the callable task is parallel, we must wait for it to return the result. Java.util.concurrent.Future was born. After the online pool submits the callable task, a future object is returned, using which we can know the status of the callable task and get the result of the execution callable returned. The future provides a get () method that allows us to wait for callable to end and get its execution results, as shown in the example code:

public class MyCallable implements Callable<String> {    @Override    public String call() throws Exception {        Thread.sleep(1000);        return Thread.currentThread().getName();    }    public static void main(String[] args) {        ExecutorService service = Executors.newFixedThreadPool(10);        List<Future<String>> list = new ArrayList<Future<String>>();        Callable<String> callable = new MyCallable();        for (int i = 0; i < 10; i++) {            Future<String> future = service.submit(callable);            list.add(future);        }        for (Future<String> fut : list) {            try {                System.out.println(new Date() + "::" + fut.get());            } catch (InterruptedException e) {                e.printStackTrace();            } catch (ExecutionException e) {                e.printStackTrace();            }        }        service.shutdown();    }}

Operation Result:

Mon Oct 06 17:24:52 CST 2014::pool-1-thread-1Mon Oct 06 17:24:53 CST 2014::pool-1-thread-2Mon Oct 06 17:24:53 CST 2014::pool-1-thread-3Mon Oct 06 17:24:53 CST 2014::pool-1-thread-4Mon Oct 06 17:24:53 CST 2014::pool-1-thread-5Mon Oct 06 17:24:53 CST 2014::pool-1-thread-6Mon Oct 06 17:24:53 CST 2014::pool-1-thread-7Mon Oct 06 17:24:53 CST 2014::pool-1-thread-8Mon Oct 06 17:24:53 CST 2014::pool-1-thread-9Mon Oct 06 17:24:53 CST 2014::pool-1-thread-10
What is the Futuretask class?

Futuretask is a canceled asynchronous compute class that implements the future interface because it can be used in executors, performing asynchronous processing operations, and in most cases we do not need the Futuretask class.
It becomes very useful only when we intend to rewrite some of the methods of the future interface and keep the original base implementation. We can just inherit from it and rewrite the methods we need.

What is a concurrent collection class?

The Java collection classes are quickly invalidated, which means that the next () method of the iterator throws an exception when the collection is changed and a thread iterates through the collection using an iterator ConcurrentModificationException .
Concurrent containers support concurrent traversal and concurrent updates. The main classes have ConcurrentHashMap , CopyOnWriteArrayList andCopyOnWriteArraySet

What is the Executors class?

Executors provides some tool methods for the Executor,executorservice,scheduledexecutorservice,threadfactory and callable classes. Executors can be used to create a thread pool conveniently.

What are the improvements to the Concurrency API in Java 8?

Some improvements are as follows:
ConcurrentHashMapImproved compute (), ForEach (), Foreachentry (), Foreachkey (), Foreachvalue (), merge (), reduce (), and Search () methods.
Completablefuture. May is explicitly completed (setting its value and status).
ExecutorsThe Newworkstealingpool () method creates a work-stealing thread pool that uses the processor currently available on the machine as its parallel level.

Java Multithreaded Interview questions
1. 进程和线程之间有什么不同?

A process is a standalone (self contained) operating environment that can be viewed as a program or an application. A thread is a task that executes in a process. The Java Runtime environment is a single process that contains different classes and programs. Threads can be called lightweight processes. Threads require fewer resources to create and reside in a process, and can share resources in a process.

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

In multithreaded programs, multiple threads are executed concurrently to improve the efficiency of the program, and the CPU does not go idle because a thread needs to wait for resources. Multiple threads share heap memory, so creating multiple threads to perform some tasks is better than creating multiple processes. For example, Servlets is better than CGI because Servlets supports multithreading and CGI does not support it.

3. 用户线程和守护线程有什么区别?

When we create a thread in a Java program, it is called a user thread. A daemon thread is a thread that executes in the background and does not prevent the JVM from terminating. When no user thread is running, the JVM shuts down the program and exits. A daemon thread creates a child thread that is still a daemon thread.

4. 我们如何创建一个线程?

There are two ways to create a thread: one is to implement the Runnable interface, then pass it to the constructor of thread, create a thread object, and inherit the thread class directly. To learn more, read this article on how to create threads in Java.

5. 有哪些不同的线程生命周期?

When we create a new thread in a Java program, its state is new. When we call the thread's start () method, the state is changed to runnable. The thread scheduler allocates CPU time to threads in the runnable thread pool and says their state changes to running. Other thread states also have waiting,blocked and dead. Read this article to learn more about the thread life cycle.

6. 可以直接调用Thread类的run ()方法么?

Sure, but if we call the thread's run () method, it behaves like a normal method, and in order to execute our code in a new thread, the Thread.Start () method must be used.

7. 如何让正在运行的线程暂停一段时间?

We can use the sleep () method of the thread class to suspend a thread for a while. It is important to note that this does not cause the thread to terminate, and once the thread is awakened from hibernation, the state of the thread will be changed to runnable, and it will be executed according to the thread dispatch.

8. 你对线程优先级的理解是什么?

Each thread has a priority, in general, a high-priority thread will have priority at run time, but this depends on the implementation of the thread schedule, which is operating system-related (OS dependent). We can define the priority of threads, but this does not guarantee that high-priority threads will be executed before the low-priority thread. The thread priority is an int variable (from 1-10), 1 represents the lowest priority, and 10 represents the highest priority.

9. 什么是线程调度器(Thread Scheduler)和时间分片(Time Slicing )?

The thread scheduler is an operating system service that is responsible for allocating CPU time to threads in the runnable state. Once we create a thread and start it, its execution depends on the implementation of the thread scheduler. Time sharding refers to the process of allocating available CPU time to available runnable threads. The allocated CPU time can be based on the thread priority or the time the thread waits. Thread scheduling is not controlled by the Java Virtual machine, so it is better to control it by the application (i.e. don't let your program depend on the priority of the thread).

10. 在多线程中,什么是上下文切换(context-switching )?

Context switching is the process of storing and recovering CPU state, which enables thread execution to resume execution from a breakpoint. Context switching is a fundamental feature of multitasking operating systems and multithreaded environments.

11. 你如何确保main()方法所在的线程是Java 程序最后结束的线程?

We can use the joint () method of the thread class to ensure that all program-created threads end before the main () method exits. Here is an article about the joint () method of the thread class.

12. 线程之间是如何通信的?

When resources are shared between threads, inter-thread communication is an important means of reconciling them. The Wait () \notify () \notifyall () method in the object class can be used to communicate between threads about the state of a lock on a resource. Click here for more on thread wait, notify and Notifyall.

13. 为什么线程通信的方法wait(), notify()和notifyAll()被定义在Object 类里?

Every object in Java has a lock (monitor, can also be a monitor) and wait (), notify (), and so on to wait for the object's lock or to notify other thread objects that the monitor is available. There are no locks and synchronizers available for any object in Java threads. That's why these methods are part of the object class, so that every class in Java has a basic method for inter-thread communication

14. 为什么wait(), notify()和notifyAll ()必须在同步方法或者同步块中被调用?

When a thread needs to invoke the object's Wait () method, the thread must have a lock on the object, and then it will release the object lock and enter the wait state until the other thread calls the Notify () method on the object. Similarly, when a thread needs to invoke the object's notify () method, it releases the lock on the object so that other waiting threads can get the object lock. Since all of these methods require a thread to hold the lock on the object, this can only be done by synchronization, so they can only be called in a synchronous method or in a synchronous block.

15. 为什么Thread类的sleep()和yield ()方法是静态的?

The sleep () and yield () methods of the thread class will run on the currently executing thread. So it makes no sense to raise these methods on other waiting threads. That's why these methods are static. They can work in the currently executing thread and prevent programmers from mistakenly thinking that these methods can be called on other non-running threads.

16 .如何确保线程安全?

There are many ways to ensure thread safety in Java-synchronization, using atomic classes (atomic concurrent classes), implementing concurrent locks, using the volatile keyword, and using immutable classes and thread-safe classes. You can learn more in the thread safety tutorial.

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

When we use the volatile keyword to modify a variable, the thread will read the variable directly and not cache it. This ensures that the variables read by the thread are consistent with the memory.

18. 同步方法和同步块,哪个是更好的选择?

Synchronizing a block is a better choice because it does not lock the entire object (you can, of course, lock the entire object). The synchronization method locks the entire object, even if there are multiple unrelated synchronization blocks in the class, which usually causes them to stop executing and to wait for a lock on the object.

19. 如何创建守护线程?

Using the Setdaemon (true) method of the thread class to set the thread as the daemon thread, it is important to note that this method needs to be called before the start () method is called, or the illegalthreadstateexception exception will be thrown.

20. 什么是ThreadLocal?

Threadlocal is used to create local variables for threads, we know that all threads of an object share its global variables, so these variables are not thread-safe and we can use synchronous technology. But when we don't want to use synchronization, we can choose the threadlocal variable.
Each thread will have their own thread variable, which can use the Get () \set () method to get their default values or change their values inside the thread. Threadlocal instances are typically the private static property that you want them to associate with the thread state. In the threadlocal example this article you can see a little program about threadlocal.

21. 什么是Thread Group ?为什么建议使用它?

Threadgroup is a class whose purpose is to provide information about thread groups.
The Threadgroup API is weak, and it does not provide more functionality than thread. It has two main functions: one is to get the list of active threads in the thread group, and the other is to set the uncaught exception handler (Ncaught exception handler) to the thread setting. However, in Java 1.5 The thread class has also added the Setuncaughtexceptionhandler (Uncaughtexceptionhandler eh) method, so Threadgroup is obsolete and is not recommended for further use.

t1.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){@Overridepublic void uncaughtException(Thread t, Throwable e) {System.out.println("exception occured:"+e.getMessage());}});
22. 什么是Java线程转储(Thread Dump ),如何得到它?

A thread dump is a list of JVM active threads, which is useful for parsing system bottlenecks and deadlocks. There are many ways to get a thread dump--using the profiler,kill-3 command, Jstack tools, and so on. I prefer the Jstack tool because it is easy to use and comes with a JDK. Since it is a terminal-based tool, we can write some scripts to generate thread dumps periodically for analysis. Read this document to learn more about generating thread dumps.

23. 什么是死锁(Deadlock )?如何分析和避免死锁?

Deadlocks are situations in which more than two threads are permanently blocked, which results in a minimum of two threads and more than two resources.

Parsing deadlocks, we need to look at thread dumps for Java applications. We need to identify the threads that are blocked and the resources they wait for. Each resource has a unique ID, which we can use to find out which threads already have their object locks.

Avoid nested locks, use locks only where needed, and avoid waiting indefinitely is the usual way to avoid deadlocks, read this article to learn how to analyze deadlocks.

24. 什么是Java Timer 类?如何创建一个有特定时间间隔的任务?

Java.util.Timer is a tool class that can be used to schedule a thread to execute at a specific time in the future. The timer class can be used to schedule one-time tasks or periodic tasks.

Java.util.TimerTask is an abstract class that implements the Runnable interface, and we need to inherit the class to create our own timed task and use the timer to schedule its execution.

Here's an example of a Java timer.

25. 什么是线程池?如何创建一个Java 线程池?

A thread pool manages a set of worker threads, and it also includes a queue that is used to place tasks that are waiting to be executed.

Java.util.concurrent.Executors provides an implementation of the Java.util.concurrent.Executor interface for creating a thread pool. The thread pool example shows how to create and use a thread pool, or read the Scheduledthreadpoolexecutor example to learn how to create a periodic task.

26.现在有T1、T2、T3三个线程,你怎样保证T2在T1执行完后执行,T3在T2执行完后执行?

This multithreading problem is relatively simple and can be implemented using the Join method.

27. 在Java中Lock接口比synchronized块的优势是什么?你需要实现一个高效的缓存,它允许多个用户读,但只允许一个用户写,以此来保持它的完整性,你会怎样去实现它?

The biggest advantage of the lock interface in multi-threaded and concurrent programming is that they provide a lock for both read and write, which satisfies high-performance data structures and conditional blocking that you write like Concurrenthashmap. The question of a Java thread interview is increasingly based on the interviewer's answer. I strongly recommend that you read locks carefully before you go to a multi-threaded interview, as it is currently heavily used to build the client cache and transaction connection space for the electronic trading final.

28.在java中wait和sleep方法的不同?

Frequently asked questions about a Java thread interview in a phone interview. The biggest difference is that wait waits for the lock to be released while sleep holds the lock. Wait is typically used for inter-thread interaction, and sleep is typically used to pause execution.

A summary of multi-thread threads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.