Dark Horse Programmer-----Java-based multi-threading

Source: Internet
Author: User
Tags ticket

Processes and Threads

Process: is the program in progress. is actually a memory space when the application is running.

Thread: A thread is a control unit or execution path within a process. The process is responsible for the labeling of the space, and the thread is responsible for executing the application execution order.

When multiple threads appear in a process, they are multithreaded. Each thread has its own execution space, method area, and variable in the stack.

A Java VM will start with a process java.exe. At least one thread in the process is responsible for the execution of the Java program, and the code that runs on the thread exists in the main method. This thread is called the primary thread.

How threads are Created

the first way to create a thread: Inherit the thread class .

Steps:

1. Define class inheritance for the thread class .

2. The Run method in the replication thread class

Purpose: Store custom code in the Run method and let the thread run.

3. Call the thread Start method .

This method has two functions: start the thread and call the Run method.

Why overwrite the Run method?

The thread class is used to describe threads. This class defines a feature that stores the code that the thread wants to run. This storage function is the Run method.

That is, the Run method in the thread class, which stores the code that the thread will run.

Threads have their own name: thread-number This number starts with 0.

Static thread CurrentThread (); Gets the current thread object.

GetName () gets the thread name.

Set the thread name: SetName () or constructor.

code example:

Class Demo extends Thread

{

public void Run ()

{

for (int x=0; x<60; x + +)

System.out.println ("Demo run----" +x);

}

}

Class Threaddemo

{

public static void Main (string[] args)

{

Demo d = new demo ();//Create a thread.

D.start ();//Open the thread and execute the thread's Run method.

D.run ();//is just the object invocation method. And the thread was created and not running.

for (int x=0; x<60; x + +)

System.out.println ("Hello World!--" +x);

}

}

Second way: Implement Runable interface

Steps:

1. Define class implementation Runable interface

2. Overwrite the Run method in the Runable interface.

Store the code that the thread is running in in the Run method.

3. Thread objects are established through the thread class.

4. Pass the subclass object of the Runable interface as the actual parameter to the constructor of the thread class. Thread (runable R)

The object to which the custom run method belongs is the subclass object of the Runable interface. So let the thread run the running method of the specified object. You must specify the object to which the Run method belongs.

5. Call the Start method of the thread class to open the thread (call the Run method in the Runable interface subclass. )

Ticketing Example:

Class Ticket implements Runnable//extends Thread

{

private int tick = 100;

public void Run ()

{

while (true)

{

if (tick>0)

{

System.out.println (Thread.CurrentThread (). GetName () + ".... Sale:" + tick--);

}

}

}

}

Class Ticketdemo

{

public static void Main (string[] args)

{

Ticket t = new Ticket ();

thread T1 = new Thread (t);//creates a thread;

Thread t2 = new Thread (t);//creates a thread;

thread t3 = new Thread (t);//creates a thread;

thread T4 = new thread (t);//creates a thread;

T1.start ();

T2.start ();

T3.start ();

T4.start ();

}

}

The difference between the two ways:

Inherit thread: The threading code holds the Run method of the thread subclass.

Implement runable: The thread code holds the run method of the subclass of the interface.

implementations avoid the limitations of single inheritance, and it is recommended to use implementations when defining threads.

Thread State :

1. Created: Wait for start, call start to start.

2. Operational status: With Executive qualification and execution rights.

3. Temporary status (blocking): There is an executive qualification, but no enforcement right.

4. Frozen state: When encountering the Sleep (time) method and the Wait () method, the execution qualification and execution is lost, and the sleep method takes the execution qualification and becomes a temporary state when the Notify () method is called.

5. The idle state: the Stop () method, or the Run method ends.

Multithreading Security Issues : When a thread is running multiple statements and manipulating the same data, other threads are involved. Causes the error data to occur.

workaround : As long as the shared data is executed by only one thread at a time, the rest of the process cannot be performed. So the synchronization sychronized (object) {The code that needs to be synchronized} is used.

The object is like a lock, the thread holding the lock can execute in the synchronization, the thread that does not hold the lock even gets the execution of the CPU, and cannot get in because the lock is not acquired

Synchronization function: The function can be modified with synchronized.

The lock is this. If the synchronization function is modified by static, the owning class.

Prerequisites for synchronization :

Must have two or more than two threads to synchronize

Multiple threads must use the same lock.

The advantage of synchronization is to solve the problem of thread safety, the disadvantage is the need to constantly judge the lock, consume resources.

Inter-threaded communication and some threading methods

Inter-thread communication is the fact that multiple threads are manipulating the same resource, but the action is different

The methods to be used are:

Wait ();

Notify ();

Notifyall ();

The above methods are used in synchronization because the thread that holds the monitor (lock) operates, so it is used in synchronization, because only synchronization has a lock

Why are the methods of these operations threads defined in the object class?

Because these methods must be used to identify the locks held by the threads they operate on when they are operating synchronously, only the same locked thread can be awakened by the same locked notify, and the threads in different locks cannot be woken up, that is, the wait and wake must be the same lock, and the lock can be any object. Therefore, methods that can be called by arbitrary objects are defined in the object class.

Deadlock issues in synchronization

When will a deadlock occur? Deadlocks occur when synchronization is nested in synchronization. At this point a thread holds a lock to be executed to get a B lock, while another thread holds a B lock to be executed to get a lock. This becomes the two threads each holding a lock, but also to obtain the other's lock, then there is a deadlock. The program will not be executed there.

Stopping a thread

Only one, therun method ends . Turn on multi-threaded running, and running code is usually a looping structure. As long as you control the loop, you can let the Run method end, that is, the thread ends.

Special cases:

When the thread is in a frozen state. The tag is not read. Then the thread will not end. When a frozen thread is returned to a running state without a specified way, the freeze needs to be purged. Forces the thread to revert to the running state. This makes it possible to manipulate the tag to end the thread. The thread class provides the method interrupt ();


This article is from the "Dot Drop" blog, please be sure to keep this source http://arctictern.blog.51cto.com/10120640/1659840

Dark Horse Programmer-----Java-based multi-threading

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.