Java Tips---Threads

Source: Internet
Author: User

1. Procedures and Processes

Q Program: A piece of static code.

Q Process: A dynamic execution process of a program, which is a complete process from which code is loaded, executed, and executed. Multi-process running has nothing to do with program development.

A Q- thread is a smaller execution unit than a process, and it is an independent control flow within a process, that is, a control flow within a program. (All of our previously written programs contain only one system flow, which starts with the main method, and goes inside each method as a call to the method, and returns to the location of the call when the method call completes, until the process ends after the main method finishes, called a system thread, This is also known as a single-threaded program. )

A Q thread is a smaller execution unit than a process. (Both the process and the threading concept make programming from serial programming (sequentially executed) into the domain of parallel programming (simultaneous execution), while the principle of implementing within the CPU is to switch on time slices)

2. Features: Threads can not run independently, must rely on the process, run in the process.

Q Each program has at least one thread known as the master path.

Q single-threaded: A process with only one thread is called a single-threaded

Q Multithreading: There are more than one thread of the process called multithreading

3. Multithreading Advantages:

(1) improve the corresponding speed of the interface program.

(2) Make full use of system resources

Insufficient Multithreading:

when the number of threads in the program is more, the system will spend a lot of time on the thread switching, which will reduce the execution efficiency of the program.

but compared to the advantages, the slight potential is still very limited, so now in the project development, multithreaded programming technology has been widely used.

4. The Java language provides two ways to implement a thread when it is actually implemented:

L inherit the thread class

L Implement runnable interface

• when implementing threading programming, you first need to have a class that is multi-threaded, inheriting the thread class or implementing the Runnable interface with multithreaded capabilities, then creating the thread object, and calling the corresponding boot thread method to achieve multithreaded programming.

L Multiple threads can be implemented in one program, which means that two or more threads are started in the same program.

L System in the execution of multithreaded software only to ensure that the thread is executed alternately, as to which thread to execute before execution, then can not be guaranteed, need to write specialized code to ensure the order of execution.

L A class has the ability to do multithreading, and you can start the thread in the location you need in the program, not just inside the main method.

L can also start multiple threads for the same thread class. The same thread cannot be started two times. For example:

You can write this:

thread T1 = new Thread ();

T1.start ();

thread T2 =new thread ();

T2.start ();

but it can't be written like this:

thread t3 = new Thread ();

T3.start ()

T3.start ()

5. The Java.lang package provides a dedicated thread class (thread) that encapsulates a number of methods for scheduling and handling threads.

to inherit the thread class to implement multithreading steps:

1). Inherit Thread class

2. Overwrite the thread class's Run method (custom thread code must be written inside the Run method)

3). Creating Threads

4). Start a thread with the Start method

Class name extends Thread {

Public Void Run ()

       {

//Thread body

        }

  }

6. Implement the Java.lang.Runnable interface and override the Runnable interface's Run method in the class.

Benefits: The multithreaded Application object can inherit other objects instead of having to inherit the thread class, which, according to the Java language syntax, can implement as many interfaces as possible, so the commonality of implementation is better than the one described earlier.

¯ 1. Implement Java.lang.Runnable interface;

¯ 2. Rewrite the Run method of the Runnable interface;

¯ 3. Create a subclass object for the Runnable interface;

¯ 4. Creates an object of the thread class and passes the subclass object of the Runnable interface as a parameter to the construction method of the thread class, and finally calls the thread object's Start method to start it.

Runnable1 r1 = new Runnable1 ();

thread T1 = new Thread (r1);

T1.start ();

7.8. New (new Thread)

when an instance (object) of the thread class is created, the thread enters the new state (not started).

For example: Thread t1=new thread ();

Q Ready (runnable)

when the start () method is invoked, the thread enters the ready state, the thread has been started, and is waiting to be assigned to the CPU time slice, which means that the thread is queuing up for CPU resources in the ready queue. If the line system does not have the ability to dial out the CPU execution time to the thread, the thread does not execute (the "no execution" here does not mean "stagnant" or "dead")

For example: T1.start ();

Q Run (running)

The thread obtains the CPU resource being executed (the run () method), and the thread runs to the end unless the thread automatically discards CPU resources or a higher priority thread enters.

U are sleeping
Use the Sleep (longt) method to get a thread into the way it sleeps. A sleeping thread can enter the ready state at a specified time.

U are waiting
Call the Wait () method. (Call Notify () method back to Ready state)

U blocked by another thread
Call the Suspend () method. (Call Resume () method restore)

Q termination status (dead)

when a thread executes or is killed by another thread, the thread enters the state of death, and the thread is no longer ready for execution.

• Natural termination: The Run () method is terminated after normal operation

U Abort: Call the Stop () method to stop a thread from running

You can test whether the thread has started by using the IsAlive () method of the Thread object.

9. The process of moving a thread from a ready state into a running state is called thread scheduling. The organization responsible for scheduling is called the dispatch manager.

Priority: The range of priority for a thread is 1~10.
Max_priority = 10
Norm_priority = 5
min_priority = 1

U get or modify the priority of the thread
Public final int getpriority ();
Public final void setpriority (int newpriority);

if more than one thread is waiting, the higher the priority is, the sooner it will be executed, just the chance to get more. Typically, therefore, do not rely on thread precedence to control the state of a thread.

10. Thread Sleep sleeping ()

executes this method to cause the current thread to sleep (stop execution) several milliseconds, the thread from the run State enters the not to run state, after the sleep time the thread then enters the running state.

suspend thread yield ()

call the yield () method to suspend the current thread execution, let the CPU resources out, and allow other threads to execute. The thread is still in a running state. Does not turn into a blocking state. At this point, the system chooses a different priority thread to execute, and if no other priority thread is available, the thread is selected to continue executing. The advantage of the yield () method is that the CPU is not idle when there is work to be done. Mainly used to write multiple cooperative threads, but also to enforce the cooperation between threads

Connect thread join ()

The join () method suspends execution of the current thread, waits for the thread that called the method to finish, and then executes the thread. It has 3 calling formats:

Public final void join () throws Interruptedexception

Public final void join (Long Millis) throws Interruptedexception

Public final void join (long millis,int Nanos) throws Interruptedexception

Interrupt thread interrupt (); The method can set a break tag for a thread, but it does not break the threads, and a thread can run after the interrupt mark is set, and the IsAlive () method returns True. So that the run () method can be detected using the isinterrupted () method. Instance method isinterrupted () tests the interrupt tag of the thread, and does not know the interrupt tag. The static interrupted () method is different, and it tests whether the currently executing thread is interrupted and, in certain cases, knows the interrupt token for the current thread object and returns True.

Public void Interrupt ()

Public Boolean isinterrupted ()

Public Static booleaninterrupted ()

11. If multiple threads simultaneously access a resource, such as variables, files, and so on, how to guarantee access security. In multithreaded programming, a resource that is accessed simultaneously by multiple threads is called a critical resource.

The order in which the threads are executed is random and uncontrolled.

The most basic solution to this problem, the simplest way is to use the synchronization key word synchronized. The Synchronized keyword is a modifier that can be decorated with a method or block of code that, for the same object (not a different object of a class), must be executed sequentially when multiple threads call the method or code block at the same time, that is to say, If two or more threads execute the piece of code at the same time, if a thread has already started executing the code, another thread must wait for the thread to finish executing the code before it can begin execution.

 

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.