Multi-Threaded Application Multithreading _ Multithreading

Source: Internet
Author: User
Tags thread class

Multi-threaded applications:
1. Network Chat tool Development
One thread is responsible for sending messages, and one for receiving messages. The two do not interfere with each other, if it is a single thread, then it may be in front of the waiting, and the following will not receive the message.
2. Replication of a large number of database records.
If a copy takes 3 days, when you halfway feel that it's unnecessary to stop, you find that you can't let him stop. And the case of multithreading, a
Ready for copy, it's an infinite loop.
while (bstop)
{Get Data
Copy data}
Another out-of-the-box supervision is whether a keyboard is pressed, that is, the variable bstop that is true is placed to false. Bstop = false; stops the program when another thread is monitoring a variable change
3.www server creates a thread for each visitor

A thread must be in one of the following four possible states, the four states of which are:

Initial state: The state in which a thread calls the new method and before calling the Start method. In the initial state, you can call the start and stop methods.
Runnable: Once the thread calls the Start method, the thread is transferred to the Runnable state, noting that if the thread is in the Runnable state it may not be running, because there are also priority and scheduling issues.

Blocking/nonrunnable: The thread is in a blocking/nonrunnable state, which is caused by two possibilities: either suspended or blocked for some reason, including waiting for the completion of the IO request.

Exit: The thread is off to the exit state, there are two possibilities, either the Run method finishes, or the Stop method is invoked.

Multithreading

1. A program is a collection of computer instructions that is stored on disk as a file.

Process: is a program execution activity in its own address space.

A process is a resource requisition, dispatch, and stand-alone unit, so it uses the running resources in the system, and the program cannot request system resources, can not be scheduled by the system, nor as a stand-alone unit, so it does not occupy the system's running resources.

Threads: A single sequential control process in a process. A process can have more than one thread.

A thread, also known as a lightweight process, has independent execution control as a process, and the operating system is responsible for scheduling, the difference being that the thread does not have separate storage space, but rather shares a single storage space with other threads in the process, making communication between threads much simpler than the process.

2.java Support for multithreading

Java provides support for multithreaded programming at the language level.

Two ways to implement multithreaded routines:

(1) Inheriting from the thread class;

(2) Implement Runnable interface.

Example:

public class ThreadTest {

/**
* @param args
*/
public static void Main (string[] args) {
Mythread mythread = new Mythread ();
Mythread.start ();
System.out.println ("main:" + Thread.CurrentThread (). GetName ());
}

}

Class Mythread extends thread{

public void Run () {
System.out.println (GetName ());
}
}

Results of printing: Main:main
Thread-0

Why the Mythread.start () is executed first and the Main:main is printed. Because the CPU that the program starts to call assigns the time slice to the main function, and when another Mythread thread is opened, the time slice that the CPU assigns to the thread of the main function does not expire, so the main function finishes System.out.println ("main:" + Thread.CurrentThread (). GetName ()), the Mythread thread begins to perform a time slice that is assigned to it by the CPU.

Background thread: When only a background thread is left in the program, the Java virtual machine exits. That is, the Java virtual machine will quit when there is no background process running in a process.

When you want to set a thread as a background thread, use the Setdaemon () method in the thread class, which must be invoked before the start () method.

2. Thread paused

The yield () method in the thread class allows the current thread to pause, allowing other threads to execute.

3. Thread Priority

The SetPriority () and GetPriority () methods in the thread class can set and get the priority of the thread.

The thread priority in the thread class has 3 kinds of max_priority, min_priority, and norm_priority, and their type is int with values of 10, 1, and 5 respectively. Setting precedence does not have to be done before the start () method, and you can modify the priority of the thread at any time. In Java, a thread has a higher priority, and it always gets the chance to execute.

Java is a scheduling model that does not support thread-time slice rotation, and uses a preemption scheduling model with high and low thread priority. A high priority thread can preempt the chance of running a low-priority thread. High-priority threads will always get the thread execution time. But this is also not absolute, the Java thread Scheduler is likely to invoke a long-running thread for execution, so do not rely on the thread's high-priority preemption model to accomplish certain functions.

The Java thread Scheduler supports preemptive methods for different priority threads, but it does not natively support the rotation of time slices for the same priority thread. However, if the operating system where the Java runtime system (such as Windows2000) supports rotation of the time slice, the thread scheduler supports the rotation of time slices for the same priority thread.

4. Calling a thread in a way that implements the Runnable interface

Package com;

public class Multithread
{
public static void Main (string[] args)
{
Mythread mt=new mythread ();
New Thread (MT). Start ();
while (true)
{
System.out.println ("Main:" +thread.currentthread (). GetName ());
}
}
}

Class Mythread implements Runnable
{
public void Run ()
{
while (true)
{
System.out.println (Thread.CurrentThread (). GetName ());

}
}
}

5. When you need to implement the run () method from the Runnable interface, when you need to derive from the thread class, to achieve multithreading.

Typically, we do not need to modify the behavior of methods other than the run () method, preferably to implement the Runnable interface. It has two advantages:

(1) When a class inherits a class, the thread class object can only be generated in a way that implements the Runnable interface.

(2) When the thread class object is generated by means of implementing the Runnable interface, the purpose of making multiple thread class objects function the same variable can be achieved.

6. Synchronization of Threads

Two ways to synchronize: synchronization block and synchronization method

(1) for the synchronized block, we need to add an object after the synchronized, which is an arbitrary object.

(2) Each object has a monitor, or is called a lock.

(3) The synchronization method utilizes the lock of the object represented by this.

(4) Each class also has a lock, which is the lock of the class object corresponding to this class. Our synchronous static method is the monitor that synchronizes the class object corresponding to this class.

7. Deadlock of Threads

(1) The question of dining philosophers

(2) Thread 1 locks the monitor of object A, waits for the monitor of object B, thread 2 locks the monitor of object B, waits for the monitor of object A, causes deadlock.

Suspend and resume methods are easy to cause deadlocks and are not recommended for use.

8.wait, notify, Notifyall

(1) For each object, in addition to a lock, there is a waiting queue (wait set), when an object just created, its waiting queue is empty.

(2) We should call the object's Wait method after the current thread locks the object's lock. (Note that the wait method can only be invoked in synchronized blocks and synchronization methods.) When the wait method is invoked, our thread enters the waiting queue of the object. )

(3) When the Notify method of an object is invoked, an arbitrarily selected thread is removed from the waiting queue of the object, and the thread becomes a running thread again. (The Notify method can only be invoked in synchronized blocks and synchronization methods)

(4) When the Notifyall method of an object is invoked, all waiting threads are removed from the waiting queue of the object, and these threads become running threads.

(5) Wait and notify are mainly used in Producer-consumer this relationship.

When you use the wait and notify methods, you must be working on the waiting queue for the same object.

9. Termination of the thread

(1) Set a flag variable.

(2) combined with interrupt () method.


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.