Java face question--thread article

Source: Internet
Author: User
Tags thread class

Java There are several ways to implement a thread? What keyword to use to modify the synchronization method ? Stop () and the suspend () How is it recommended?

Java5 before, as in the following two kinds:

The first type:

New Thread () {}.start (); This means that the run method of the thread subclass object is called , andnew Thread () {} represents an instance object of an anonymous subclass of thread, with the subclass plus The code after the Run method is as follows:

1 New Thread () {23              Public void run () {45            }67         }. Start ();


The second type:

New Thread (New Runnable () {}). Start (); This means that the run method of the Runnable object accepted by the Thread object is called , andnew Runnable () {} represents a An instance object of the anonymous subclass of Runnable, with the following code for the subclass of Runnable plus the Run method:

1 new Thread (new Runnable () {2 3 public             void                    }8 9         ). Start ();  

starting with Java5, there are a number of thread pools that create multithreading:

1Executorservice pool = Executors.newfixedthreadpool (3);2 3          for(inti = 0; I < 10; i++)4 5         {6 7Pool.execute (Newrunable () {8                  Public voidrun () {9                 }Ten             }); One  A         } -  -Executors.newcachedthreadpool (). Execute (Newrunable () { the              Public voidrun () { -             } -         }); -  +Executors.newsinglethreadexecutor (). Execute (Newrunable () { -              Public voidrun () { +             } A         } at  -);

Using the synchronized keyword to modify the synchronization method

Against the use of Stop () is because it is unsafe. It unlocks all locks acquired by the thread, and if the object is in an incoherent state, then other threads can examine and modify them in that state. The result is hard to check out the real problem.

The suspend () method is prone to deadlocks. when calling suspend (), the target line routines stops, but still holds the lock that was acquired before. At this point, no other thread can access the locked resource unless the thread that is "suspended " resumes running. For any thread, if they want to restore the target thread while trying to use any of the locked resources, it will cause a deadlock. So instead of using suspend (), you should place a flag in your own thread class that indicates whether the thread should be active or suspended. If the flag indicates that the thread should hang, use wait () to enter the wait state. If the flag indicates that the thread should be resumed, restart the thread with a notify ().

sleep () and the Wait () What's the difference? ?

Sleep is the thread that is being executed to voluntarily make up the CPU, theCPU to execute other threads, and after the time specified by sleep, theCPU will go back to the thread and continue execution, if the current thread has entered a sync lock, The Sleep method does not release the lock, even if the current thread uses the sleep method to give out the CPU, but other threads that are blocked by the sync lock cannot be executed.

Wait refers to a thread that has entered a sync lock, allowing itself to temporarily let out a sync lock so that other threads waiting for the lock can get a synchronous lock and run, and only other threads call the notify Method (notify does not release the lock, just tells the call The thread of the wait method can go to the competition to get the lock, but not immediately get the lock, because the lock is still in the hands of others, others have not yet released. If the code behind the Notify method is a lot more, it needs to be executed before releasing the lock, you can add a wait and some code after the Notfiy method, see the effect, and the thread that calls the Wait method will dismiss The wait state and the program can get the lock again after continuing to run down.

what are the similarities and differences between synchronous and asynchronous, and under what circumstances are they used separately? An example is described.

If the data will be shared between threads. For example, the data being written may be read by another thread later, or the data being read may have been written by another thread, then the data is shared and must be accessed synchronously.

When an application calls a method that takes a long time to execute on an object and does not want the program to wait for the method to be returned, it should use asynchronous programming, which is often more efficient in many cases with asynchronous approaches.

There are several ways to implement multithreading ? There are several ways to implement synchronization   ?

There are two ways to implement multithreading, namely, inheriting the thread class and implementing the Runnable interface .

There are two implementations of synchronization, namely Synchronized,wait and notify

Wait (): causes a thread to be in a wait state and releases the lock of the object it holds .

Sleep (): Makes a running thread sleep, is a static method that calls this method to catch the interruptedexception exception.

Notify (): Wakes up a waiting thread, noting that when this method is called, it does not actually wake up a waiting state thread, but is determined by the JVM to wake up which thread, and not by priority.

Notityall (): Wakes all the threads that are in the waiting state, noting that they do not give all the wake-up threads an object lock, but instead let them compete.

start a thread with run () or start ()?

Starting a thread is calling the start () method, making the thread-ready state, which can later be dispatched to a running state, a thread must correlate some specific execution code, and therun () method is the execution code associated with the thread.

When a thread enters one of the object's synchronized methods, does the other thread have access to other methods of this object ?

In several cases:

1. Whether the Synchronized keyword was added before other methods , if not added, it can.

2. If wait is called internally by this method , you can enter another synchronized method.

3. If all other methods add the synchronized keyword and no wait is called internally , you cannot.

The basic concepts of threads, the basic state of threads, and the relationship between States

A program can have more than one execution thread execution, a thread is an execution thread in the program, each thread is associated with the code to execute, that can have more than one program code running at the same time, each program at least a thread, that is, the Main method executes the thread. If it's just a CPU, how can it execute multiple programs at the same time? This is from the macroscopic point of view, theCPU will execute a clue, a will execute b clue, switch time quickly, give a person's feeling is a , b at the same time, like everyone in the same office Internet, only one link to the external network cable, in fact, this cable will be a data, a b data, because the switching time is very short, so, everyone feels at the same time the Internet.

Status: Ready, running,synchronize blocking,wait and sleep hangs, end. wait must be called inside the synchronized.

After invoking the thread's start method, the thread goes into a ready state, the thread dispatch system turns the thread of the ready state into the running state, and when it encounters the synchronized statement, it becomes blocked by the running state, and when the synchronized gets the lock, the block shifts to run. In this case, you can call the wait method to the pending state, and when the thread-associated code finishes executing, the thread becomes the end state.

Brief Introduction of similarities and differences between synchronized and java.util.concurrent.locks.Lock ?

Main similarities: Lock can complete all functions implemented by synchronized

Main differences: Lock has more precise line semantics and better performance than synchronized. The synchronized automatically releases the lock, and lock must require the programmer to release it manually, and must be released in the finally clause. Lock also has a more powerful function, for example, its Trylock method can be non-blocking way to get the lock.

Java face question--thread 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.