Java Thread Cheng

Source: Internet
Author: User

/* Simple ticket selling procedure to implement multiple windows to sell tickets at the same time *
/*
Creating a ready-made second method: implementing the Runnable Interface

Steps:
1, defines the class implementation runnable interface. There is only one abstract method in the Runnable interface, which is the Run method.
2, overwrite the Run method in the Runnable interface.
Put the code for the thread to run in this run method.
3, the thread object is established through the thread class.
4, pass the subclass object of the Runnable interface as the actual parameter to the constructor of the thread class.
Why pass the subclass object of the Runnable interface to the thread's constructor?
Because the object that the custom run method belongs to is the subclass object of the Runnable interface, the object to which the Run method belongs must be defined if the thread is to run the specified object's Run method.
5, call the Start method of the thread class to open the thread and invoke the Run method of the Runnable interface subclass.

The difference between implementation and inheritance: (It is often used to implement the Runnable interface mode)

The benefits of the implementation approach: avoid the limitations of single inheritance, and one class cannot inherit the thread class if it inherits other classes. Then, if you want to have multi-threaded functions, you can implement the method of Runnable interface.
It is recommended to use implementations when defining threads.

The difference between the two ways:
Inheritance mode: Inherit the thread class >>>> line animations in the Run method of the thread subclass.
Implementation mode: Implement Runnable interface >>>> line animations in the Run method of the subclass of the interface. Sharing data
*/
/*
In fact, multithreading is a security hidden problem. such as the example of selling tickets.
When there are four threads for simultaneous ticketing, there will be a security problem with the wrong ticket. To illustrate:
When there is a ticket (the ticket is a shared data of several threads), if thread 1 is executed, it passes through if judgment statement, but has not issued the ticket to enter the frozen state (pause on the execution path), at this time the ticket is not sold
Thread 2 also goes through the IF statement and then freezes on the execution path, as are threads 3 and 4. When thread 1 is executed, the last ticket is sold, and the thread 2,3,4 will sell the wrong ticket because there is no ticket in effect.

The cause of the problem: when multiple statements operate on the same "thread-sharing data", a thread executes only a portion of multiple statements, not finished,
Solution to the security problem: only one thread can execute the "multiple operations shared data statement" at a stroke, that is, it cannot be interfered by other threads or participate in the operation while performing the operation sharing data.

Java provides a professional solution to multi-threaded security issues: synchronizing code blocks.


Synchronized (object)//Take this object as a lock
{
Code that needs to be synchronized (look directly at the code that operates on the shared data.) Put them in curly braces)
}

Objects are like locks, and the resulting thread can execute in synchronization.
A thread that does not hold a lock even gets the execution of the CPU, and cannot get in because there is no lock. The principle of the synchronization mechanism to solve the security problem is similar to the principle that many people on the train go to the bathroom, only one at a time, and lock.

Prerequisites for synchronization:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In particular, in the simultaneous use of synchronization functions and synchronization of blocks of code, the lock in the synchronization block to use the This keyword.
1, must have two or more than two threads;
2, the same lock must be used by multiple threads.

You must ensure that only one thread in the synchronization is running.

Benefits: Solve the problem of multithreading security;
Cons: Multiple threads need to determine the lock and consume more resources.


!!!!!!!!!!!!!! Synchronization function!!!!!!!!!!!!
The lock used by the non-static synchronization function is this. The function needs to be called by the object, so the function has a reference to the owning object. This is the. So the lock used by the sync function is this. Each thread is an object of thread,

Use two threads to sell tickets:
1, a thread in the synchronization code block;
2, a thread in the synchronization function;
Are executing the ticket sales action.


Static synchronization function///////////////
If the synchronization function is statically decorated, what is the lock used?
This is not found by validation because the this is not defined in a static method.
Note that there is no such object in memory when it is statically in memory, but there must be a byte-code file object corresponding to that class.
Class name. The type of the object is class.

*/
Class Tacket implements Runnable//extends thread{private static int sum=200;//sum is a shared data that is placed in heap memory and all threads access this shared data. After a thread has finished running, the shared data is modified synchronously. Object Obj=new Object (), Boolean flag=true;public void Run () {if (flag) {while (true) {synchronized (Tacket.class)///synchronous code block, Store the code that needs to be synchronized. {if (sum>0)//operation shared Data {try{thread.sleep (10);}  catch (Interruptedexception e) {}system.out.println (Thread.CurrentThread (). GetName () + "Run" +sum--); Operation shared Data}}}}elsewhile (true) show ();} public static synchronized void Show () {if (sum>0)//operation shared Data {try{thread.sleep (20);}  catch (Interruptedexception e) {}system.out.println (Thread.CurrentThread (). GetName () + "Run" +sum--);   Operation shared data}}}class tacketdemo{public static void Main (string[] args) {tacket t=new tacket (); Only one ticket object is created, and all threads share data for this object, including the total number of votes Sumthread t1=new Thread (t), or the subclass object of the Runnable interface as a parameter to the thread class's constructor. The intent is that the thread runs the Run method in the subclass object. Thread t2=new thread (t); T1.start (); Try{thread.sleep (10);} catch (Interruptedexception e) {}t.flag=false;t2.start ();//thread t3=new thread (t);//thread t4=new thread (t);//t3.start ();//t4.start ();//t1.start ();//An exception occurs because the thread T1 has been opened without being opened again. System.out.println ("Hello world!");}}

Java Thread Cheng

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.