Java basics --- thread issues, java basics ---

Source: Internet
Author: User
Tags try catch

Java basics --- thread issues, java basics ---
1: Inherit the Thread class. Why should we inherit the run method?

Answer: Thread implements the Runnable interface,

The run method is the Runnable method, and the method in the interface
The default value is public abstract. If the Thread class is inherited and the run method is not overwritten, no error is reported, but
Set the code for running the thread.

2: differences between processes and threads

Answer: A process is a running activity of a program with certain independent functions. It is an independent unit for the system to allocate and schedule resources.
A thread is an entity of a process and the basic unit of CPU scheduling and scheduling. It is a smaller basic unit than a process that can run independently. A thread basically does not own system resources, only one resource (such as program counters, a set of registers and stacks) is essential for running. One thread can create and withdraw another thread;
Relationship between processes and threads:
① A thread can belong to only one process, and a process can have multiple threads, but at least one thread.
② Resources are allocated to the process. All threads of the same process share all resources of the process.
③ The thread must collaborate and synchronize during execution. Message Communication is required between threads of different processes for synchronization.
④ The processor is allocated to the thread, that is, the thread that actually runs on the processing machine.
⑤ A thread is an execution unit in a process and a schedulable entity in the process.
Differences between threads and processes:
① Scheduling: A thread is the basic unit for scheduling and allocation, and a process is the basic unit for resource ownership.
② Concurrency: not only can concurrent execution be performed between processes, but also between multiple threads of the same process.
③ Possess resources: a process is an independent unit of resources. A thread does not possess system resources, but can access resources belonging to a process.
④ System overhead: when a process is created or abolished, resources must be allocated and recycled by the system, resulting in a significant overhead greater than the thread creation or cancellation. But the process has an independent address space. After the process crashes, it will not affect other processes in the protection mode, and the thread is only a different execution path in the process. A thread has its own stack and local variables, but there is no separate address space between threads. If a thread dies, the whole process dies. Therefore, multi-process programs are more robust than multi-threaded programs, however, during process switching, resources are consumed and the efficiency is lower.

The thread division scale is smaller than the process, making the multi-thread program highly concurrent. In addition, the process has independent memory units during execution, and multiple threads share the memory, which greatly improves the program running efficiency. During the thread execution, each independent thread has an entry for program execution, sequence execution sequence, and program exit. But the thread cannot be executed independently. It must exist in the application, and an application provides multiple thread execution control.

From a logic point of view, the meaning of Multithreading is that, in an application, multiple execution parts can be executed simultaneously. However, the operating system does not view multiple threads as multiple independent applications to implement process scheduling, management, and resource allocation. This is an important difference between processes and threads.

3: Conditions for deadlock

When a deadlock occurs, there are four necessary conditions: ① mutex: There are mutually exclusive resources, that is, critical resources; ② waiting for resources: Processes with resources are waiting for other resources; ③ non-Deprivation: resources occupied are the resources that cannot be deprived of use; ④ cyclic waiting: resources are waiting for each other.

4: What is the difference between the Synchronized lock and lock?

① The synchronized lock only locks the code content in the brackets, a method or a class. If the lock code throws an exception, the lock resource is automatically released.

② The code between lock and unlock is locked. The locked code throws an exception and will not automatically release the lock resource. You need to try catch and manually unlock the lock resource in finally to release the lock resource.

5. Synchronization and lock in multiple threads

The Lock replaces synchronized, while the Condition replaces the monitor method (wait, y, policyall) in the Object. The Condition can be obtained through the Lock and one Lock can correspond to multiple conditions.

Class Resource {private String name; private int count = 1; private boolean flag = false; // defines the flag for switching between processes private Lock lock = new ReentrantLock (); private Condition con = lock. newCondition (); // private Condition con_pro = lock. newCondition (); // private Condition con_con = lock. newCondition (); // an exception is thrown here. Remember to handle the exception when processing the thread public void set (String name) throws InterruptedException {lock. lock (); // lock, lock () and unlo Ck () is actually similar to synchronized, but lock must be manually locked and unlocked try {while (flag) con. await (); // thread wait, similar to wait // con_pro.await (); this. name = name + "-->" + count ++; System. out. println ("producer .. "+ this. name); flag = true; con. signalAll (); // wake up all threads, similar to policyall // con_con.signal ();} finally {lock. unlock (); // release lock} // an exception is thrown here. Remember to handle the exception when processing the thread public void out () throws InterruptedException {lock. lock (); // lock try {while (! Flag) con. await (); // thread wait // con_con.await (); System. out. println ("consumer .. "+ this. name); flag = false; con. signalAll (); // wake up the thread // con_pro.signal ();} finally {lock. unlock (); // release lock }}// the Code Annotated above realizes the function of waiting for the local thread and only awakening the thread of the other party.
6: Why is stop inappropriate in multiple threads?

Multithreading is generally related. If the thread is stopped with stop, it is easy to forcibly interrupt the connection between threads and cause errors.

7: differences between Synchronous Code blocks and synchronous Methods

The key held by the synchronization method is this, which is the class object. The synchronization code block can be customized with the syntax synchronized (object) {synchronous content}. Of course, this object can also be this. The scope of the synchronous code block is smaller than that of the synchronous function. The scope of the synchronous function is greater than that of the synchronous code block, and the efficiency of the synchronous code block is relatively higher.

8: difference between Sleep and wait

① Sleep is in the Thread class and wait is in the Object; ② sleep will automatically wake up after the specified time. wait requires other threads to call y or yyall to wake up; ③ sleep the biggest feature is who calls and who sleeps. Even if Class a calls the sleep method of Class B, Class a actually goes to bed. ④ Wait can only be used in synchronous control methods or synchronization control blocks, and sleep can be used anywhere. ⑤ the thread holding the lock executes sleep without releasing the lock, when the thread holding the lock executes to wait (), the lock is released.

9: five States and features of a thread

① New state (New): A New thread object is created.
② Ready state (Runnable): After the thread object is created, other threads call the start () method of the object. the thread in this status is located in the runable thread pool and becomes runable, waiting to obtain the CPU usage right.
③ Running status (Running): The ready thread obtains the CPU and executes the program code.
④ Blocking status (Blocked): the blocking status indicates that the thread gives up CPU usage for some reason and stops running temporarily. it is not until the thread enters the ready state that it has the opportunity to go to the running state. blocking is divided into three types: A) waiting for blocking: The Running thread executes the wait () method, and the JVM puts the thread into the waiting pool. B) Synchronization blocking: When a running thread obtains the synchronization lock of an object, if the synchronization lock is occupied by another thread, the JVM puts the thread into the lock pool. C) Other blocking: When the running thread executes the sleep () or join () method or sends an I/O Request, JVM sets the thread to blocking. when the sleep () status times out and the join () waits for the thread to terminate or times out or the I/O processing is completed, the thread re-transfers

10: Synchronous function lock
Public class Demon {// 1. static Method synchronization function public static synchronized void method1 () {}// 2. non-static method synchronization public synchronized void method2 () {}// 3. this method can be equivalent to the static method synchronization function, that is, the static method synchronization function omitting the lock as Demon. class static code block, because the static method is called by the class itself, and each class is loaded with the class bytecode during initialization, the lock is Demon. class public void method3 () {synchronized (Demon. class) {}}// 4 this method can be equivalent to a non-static method to synchronize functions, that is, the underlying implementation principle of non-static methods // note that the lock of the static code block is this, because a function needs to be called by an object, all functions have an object reference, so this is used. Public void method4 () {synchronized (this) {}} // You can synchronize multiple threads and share data with other operations .}

 



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.