Java Essentials---threading issues

Source: Internet
Author: User
Tags try catch

1: Inherit the Thread class, why inherit the Run method

Answer: Thread implements the Runnable interface,

The Run method is a Runnable method, and the method in the interface
Default public abstract. If you inherit the Thread class, do not rewrite the Run method without error, but you cannot refer to
Code that runs on the thread.

2: The difference between process and thread

Answer: A process is a program with a certain independent function on a data set on a running activity, is the system for resource allocation and scheduling of an independent unit.
A thread is an entity of a process, a basic unit of CPU Dispatch and dispatch, and a smaller unit that can run independently than a process, and the thread itself does not own the system resources, but has only a few resources (such as program counters, a set of registers and stacks) that are necessary to run, and one thread can create and revoke another thread;
Relationship of process and thread:
① a thread can belong to only one process, while a process may have multiple threads, but at least one thread.
The ② resource is allocated to the process, and all the threads of the same process share all the resources of the process.
③ threads require collaborative synchronization during execution. Synchronization is achieved between threads of different processes using the means of message communication.
The ④ processor is assigned to a thread, that is, a thread that is actually running on the processing machine.
A ⑤ thread is an execution unit within a process and a scheduled entity within a process.
The difference between a thread and a process:
① Scheduling: A thread acts as the basic unit of dispatch and allocation, and processes as the basic unit of resources.
② Concurrency: Not only can concurrent execution between processes, but also concurrent execution between multiple threads of the same process.
③ owns a resource: a process is an independent unit that owns resources, and threads do not own system resources, but can access resources that belong to the process.
④ system overhead: When creating or revoking a process, the system is significantly larger than the cost of creating or revoking a thread, because the system allocates and reclaims resources for it. However, the process has a separate address space, and after the process crashes, it does not affect other processes in protected mode, and the thread is just a different execution path in a process. Thread has its own stack and local variables, but there is no separate address space between the threads, a thread dead is equal to the entire process dead, so the multi-process program is more robust than multithreaded programs, but in the process of switching, the cost of large resources, the efficiency is worse.

The thread's dividing scale is smaller than the process, which makes the multi-thread procedure high concurrency. In addition, the process has independent memory units during execution, while multiple threads share memory, which greatly improves the efficiency of program operation. During the execution of the thread, each separate thread has a program running the entry, sequentially executing the sequence and the exit of the program. But threads are not able to execute independently, and must be dependent on the application, with the application providing multiple threads of execution control.

From a logical point of view, the meaning of multithreading. With an application, there are multiple execution parts that can be executed at the same time. However, the operating system does not consider multiple threads as separate applications to implement scheduling and management of processes and resource allocation. This is the important difference between processes and threads.

3: Condition of deadlock

There are 4 necessary conditions for a deadlock: ① mutual exclusion: the existence of mutually exclusive use of resources, that is, critical resources; ② occupy the waiting: the process of owning resources is waiting for additional resources; ③ is not deprived: the resources occupied are the inalienable resources; ④ Cycle waits: All are waiting for resources.

What is the difference between a 4:synchronized lock and a lock lock?

①synchronized Lock locks Only the contents of the code inside the parentheses, a method or a class, and so on. If the locked code throws an exception, the lock resource is freed automatically.

②lock Lock locks the code between lock and unlock, the locked code throws an exception does not automatically release the lock resource, requires a try catch after the manually unlock release lock resource in the finally.

5: Synchronization and locking in multiple threads

Lock replaces synchronized, while Condition replaces the Monitor method (Wait,notify,notifyall) in Object, Condition can be obtained by lock Lock, and a lock can correspond to multiple Con Dition.

classresource{PrivateString name;Private intCount = 1; Private BooleanFlag =false;//Define flags for inter-process switching PrivateLock lock =NewReentrantlock ();PrivateCondition con =lock.newcondition ();//private Condition Con_pro = Lock.newcondition ();//private Condition Con_con = Lock.newcondition ();//exception is thrown here, you must remember to do exception handling when processing threads  Public voidSet (String name)throwsinterruptedexception{Lock.lock ();//locked, Lock () and unlock () are actually similar to synchronized, just lockmust be manually locked and unlockedTry{  while(flag) con.await ();//thread waits, 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 Notifyall//con_con.signal ();} finally{lock.unlock ();//Release Lock } }//exception is thrown here, you must remember to do exception handling when processing threads  Public voidOut ()throwsinterruptedexception{Lock.lock ();//locked Try{  while(!flag) con.await ();//Thread Waits//con_con.await ();SYSTEM.OUT.PRINTLN ("Consumer ..." + This. Name); Flag=false; Con.signalall ();//wake-Up thread//con_pro.signal (); } finally{lock.unlock ();//Release Lock } }}//the code of the above comment realizes the function of waiting for the line Rountines accesses to wake the other thread. 
6: Stop in multi-threading why not appropriate

Multithreading is generally connected, if you stop the thread with stop, it is easy to forcibly interrupt the connection between the threads, prone to error.

7: Differences between synchronous code blocks and synchronization methods

The key that the synchronization method holds is this, which is the object of this class. The synchronization code block can customize a lock, the syntax is: synchronized (object) {synchronous content}, of course, this object can also be this. The scope of the synchronization code block is smaller than the synchronization function, and the scope of the synchronization function is larger than the synchronous code block, and the synchronization code block is relatively efficient.

The difference between 8:sleep and wait

①sleep is in the Thread class, wait is in Object, ②sleep automatically wakes after a specified time, and wait calls notify or Notifyall wake from other threads; ③sleep has one of the biggest features is who calls, who sleeps , even if you call B's Sleep method in Class A, actually a goes to sleep. ④wait can only be used in a synchronous control method or in a synchronization control block, and sleep can be used anywhere, ⑤ the thread holding the lock executes sleep, does not release the lock, and the thread holding the lock executes to wait () when the lock is released.

9: Five states and features of threads

① new state: A new Thread object was created.
② ready State (Runnable): After the thread object is created, other threads call the object's start () method. The state of the thread is in a running thread pool that becomes operational and waits for the CPU to be used.
③ Run State (Running): The ready state of the thread gets the CPU and executes the program code.
④ blocking State (Blocked): Blocking state is a thread that temporarily stops running because it abandons the CPU for some reason. Until the thread is in a ready state, there is a chance to go to the running state. There are three blocking scenarios: A) Waiting for blocking: The running thread executes the wait () method, the JVM The thread is put into the waiting pool. B) Synchronous blocking: When a running thread acquires a synchronization lock on an object, the JVM puts the thread into the lock pool if the synchronization lock is occupied by another thread. C) Other blocking: When the running thread executes the sleep () or join () method, or when an I/O request is made, the JVM will place the thread in a blocking state. When the sleep () state timeout join () waits for the thread to terminate or the time-out or I/O processing is complete, the thread is re-transferred to

10: Sync function Lock problem
 Public classDemon {//1. Static method Synchronization function  Public Static synchronized voidmethod1 () {}//2. Non-static method synchronization  Public synchronized voidmethod2 () {}//3. This method can be equivalent to the static method synchronous function, that is, the static method synchronization function omitted the lock to Demon.classStatic blocks of code, because static methods are called by the class itself, and each class is initialized to load theclassbyte code, so the lock is Demon.class  Public voidmethod3 () {synchronized(Demon.class){} }//4 This method can be equivalent to the non-static method synchronous function, that is, the non-static method underlying implementation principle//Note that at this time, the lock of the static code block is this, because the function needs to be called by the object, then the function has aThe owning object reference, so use the This.  Public voidmethod4 () {synchronized( This){} }//synchronization is generally a multi-threaded scenario, and involves manipulating shared data. }



Java Essentials---threading issues

Related Article

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.