Java multithreaded Programming Core technology----experience 1

Source: Internet
Author: User
Tags object object ticket

1. Threads and processes

There are many examples of processes and threads, because it is a learning note, that is, I feel very good understanding, is that we use the QQ every day, But we run the QQ.exe program, the process begins, we can open the Chat window at the same time, can be more than one video, and even the video side of the manual chat (maybe the sound is broken ...) Each of these tasks can be fully understood as a "thread" in the work, music, image emoticons, files and other functions have a corresponding thread in the background silently run.

2 using Multithreading 2.1. How can 11 classes become "threads"?

Before answering the above questions, let us first recognize a class and an excuse, the thread class and the runnable excuse. There are two ways to implement multithreaded programming

1) inherit the thread class (Java is characterized by a single inheritance, if a class must inherit another class, but also want to implement the thread, then the thread class will not be done)

2) Implement runnable excuses (support "multi-inheritance" on the pretext of runnable, one side of the implementation of inheritance, but it is only the way that the thread created by the nature of the work is the same)

Inherit the thread class

Let us first look at the source code thread class structure (in fact, the thread class is also the implementation of the runnable excuse)

public class Thread implements Runnable

Here's a simple code to implement a thread that uses the inherited thread class

Package test;

public class ThreadDemo01 {
public static void Main (string[] args) {

Testthread tt=new testthread ();//Create Thread object
Tt.start ();//Activating a thread
for (int i=0;i<5;i++) {
System.out.println ("Main thread is running");
try {
Thread.Sleep (2000);//Sleep 2s
} catch (Exception e) {
Todo:handle exception
}
}

}

}

Class Testthread extends thread{

public void Run () {//Override parent class Run method
for (int i=0;i<5;i++) {
System.out.println ("Testthread is running");
try {
Thread.Sleep (1000);//sleep 1 seconds
} catch (Exception ex) {
Todo:handle exception
Ex.printstacktrace ();
}

}

}

}

The code from the above needs to be noted: 1) The Class of the thread class of the process must be written from the Run method. 2) activating a thread using the Start method (actually changing the state of the thread)

3) If you run more than two times this program you will find that the results are different, which shows that the multi-threaded execution sequence is indeterminate (mainly see the length of CPU time slices)

Make runnable excuses

Directly on the code

Package test;

public class ThreadDemo02 {
public static void Main (string[] args) {
Testthread tt=new Testthread ();
New Thread (TT). Start ();//Activate a thread
for (int i=0;i<5;i++) {
System.out.println ("Main is running");
try {
Thread.Sleep (1000);
} catch (Exception e) {
Todo:handle exception
}
}
}

}
Class TestThread02 implements Runnable {

@Override
public void Run () {
for (int i=0;i<5;i++) {
System.out.println ("Testthread is running");
try {
Thread.Sleep (1000);

} catch (Exception e) {
Todo:handle exception
}
}

}

}

To achieve runnable excuses need to note: 1) Although I realized the runnable excuse,  However, the start method of the thread class is still used to activate the thread (because there is no other way to view the JDK document that Runnable has only one run method) 2) The constructor public thread of the thread class (Runnable Target) can instantiate an object of the thread class as an argument for an implementation class object that is an excuse

instance variables and thread safety

Instance variables in a custom thread class can have shared and unshared points for other threads. This is also an important point of knowledge when multithreading is interactive.

Here is an example of buying a ticket, the train ticket has a lot of the point of generation, now requires four generations to sell out a total of 5 tickets,

Scenario 1 using methods that inherit the thread class

Package test;

public class ThreadDemo03 {
public static void Main (string[] args) {
TESTTHREAD03 t=new TestThread03 ();

A thread object object can only start one thread
T.start ();
T.start ();
T.start ();
T.start ();
}

}
Class TestThread03 extends thread{
private int i=5;
public void Run () {
while (i>0) {
System.out.println (Thread.CurrentThread (). GetName () + "ticketing" +i);
I-=1;
}
}
}

Execution will find the exception java.lang.IllegalThreadStateException this means that the notation cannot be "votes shared" and that an object can only start one thread

Look again at Scenario 2

Package test;

public class ThreadDemo03 {
public static void Main (string[] args) {
TESTTHREAD03 t=new TestThread03 ();
New TestThread03 (). Start ();
New TestThread03 (). Start ();
New TestThread03 (). Start ();
New TestThread03 (). Start ();
}

}
Class TestThread03 extends thread{
private int i=5;
public void Run () {
while (i>0) {
System.out.println (Thread.CurrentThread (). GetName () + "ticketing" +i);
I-=1;
}
}
}

From the execution of the results are four threads, but the number of votes is wrong, so it appears that each thread 5 tickets, and our original intention 4 threads sold 5 tickets Seriously inconsistent, then we will make a small change, the variable i set to static variable

Scenario 3

Package test;

public class ThreadDemo03 {
public static void Main (string[] args) {
TESTTHREAD03 t=new TestThread03 ();
New TestThread03 (). Start ();
New TestThread03 (). Start ();
New TestThread03 (). Start ();
New TestThread03 (). Start ();
}

}
Class TestThread03 extends thread{
private static int i=5;
public void Run () {
while (i>0) {
System.out.println (Thread.CurrentThread (). GetName () + "ticketing" +i);
I-=1;
}
}
}

From the implementation of the results see seems to complete the resource sharing requirements, but we found that some tickets appear "one vote more sell" phenomenon, this is not a thread safety problem, this later solve, first look at using runnable excuse how to complete the resource sharing

Run the following code

Scenario 4

Package test;

public class ThreadDemo03 {
public static void Main (string[] args) {
TESTTHREAD03 t=new TestThread03 ();
New Thread (t). Start ();
New Thread (t). Start ();
New Thread (t). Start ();
New Thread (t). Start ();
}

}
Class TESTTHREAD03 implements runnable{
private int i=5;
public void Run () {
while (i>0) {
System.out.println (Thread.CurrentThread (). GetName () + "ticketing" +i);
I-=1;
}
}
}

Comparing Scenario 4 and Scenario 3, using the runnable excuse seems to have an advantage over using the thread class

Now talk about non-threading security.

The previous scenario 3 and Scenario 4 addressed the issue of resource sharing, but there was a problem with multiple threads selling one ticket (reason: Assuming that the votes are now 5, thread 1 saw, executed the Run method, the number of votes was reduced by 1 but then thread 1 CPU time slices, must exit, change other threads, At this point, the thread 2 still sees is the ticket number of i=5, so it has sold again)

To solve this problem to achieve a ticket to buy must be quoted keyword synchronized (make ... Synchronization

Syntax format with no code block:

Synchronized (object) {

Code that needs to be synchronized

}

Or execute the code first

Package test;

public class ThreadDemo04 {

public static void Main (string[] args) {
TESTTHREAD04 t=new TestThread04 ();
New Thread (t). Start ();
New Thread (t). Start ();
New Thread (t). Start ();
New Thread (t). Start ();
}

}
Class TESTTHREAD04 implements runnable{
private int i = 5;
@Override
public void Run () {
while (true) {
Synchronized (this) {
if (i<=0) {
Break
}
System.out.println (Thread.CurrentThread (). GetName () + "ticketing" +i);
I-=1;
}
}

}

}

The purpose of using the synchronized code block is to ensure that the content is atomic (either not executed, execution must be executed, there is no half-execution interruption)

And at the same time entering the critical section (synchronized code block) can only have one thread

Not only can you use code blocks but also synchronized-modified methods to address "non-threading security issues"

Execute the following code:

Package test;

public class ThreadDemo06 {
public static void Main (string[] args) {
TestThread06 t=new TestThread06 ();
New Thread (t). Start ();
New Thread (t). Start ();
New Thread (t). Start ();
New Thread (t). Start ();
}

}
Class TestThread06 implements runnable{
private int i=5;
@Override
public void Run () {

while (i>0) {
Sale ();
}

}
Public synchronized void Sale () {
if (i>0)
System.out.println (Thread.CurrentThread (). GetName () + "ticketing" +i);

try {
Thread.Sleep (1000);
} catch (Exception e) {
Todo:handle exception
}
I-=1;
}


}

Cond.. Daughter-in-law Let me sleep

Java multithreaded Programming Core technology----experience 1

Related 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.