Java multi-thread thread&&runnable sample

Source: Internet
Author: User

Watched a video, well, recorded under the deepened understanding ... There are two ways to implement multithreading in Java: Inheriting the thread class, which is caused by a single inheritance of Java; Another way is to implement the Runnable interface, which avoids the pitfalls caused by the thread approach due to Java single inheritance. What you need to know is that the thread starts to preempt the CPU, and if a thread is currently new, the thread will go into the created state, and then we start the thread, Thread.Start (), at which point the thread will be ready, and if CPU resources are currently available, Then it is in the running state, if the sleep method or some blocking event is performed at this time, it will cause the thread to be blocked, then sleep to a certain time after blocking, will continue to queue to ready state, continue to wait for the current release of the CPU to release resources, if the Run method is completed, Then the thread terminates and is automatically destroyed. This is why not add synchronized words will appear disorderly order situation. Because you have entered the thread queue, but the current CPU resources are not necessarily you get, will be from behind. That means you may have started (), but not necessarily run () first.

Simulate selling tickets using inheritance thread

public class Soldticketthread extends Thread {
private int ticket = 5;
private String name;

Construction method
Public Soldticketthread (String name) {

THIS.name = name;

}

    public void Run () {
        while (Ticket > 0) {
&nbs p;           System.out.println (name + "sold a ticket, remaining" + (--ticket) + " Ticket ");
       }
   }

public static void Main (string[] args) {
Create three threads, simulate three windows sell tickets
Soldticketthread wd1 = new Soldticketthread ("window One");
Soldticketthread wd2 = new Soldticketthread ("window Two");
Soldticketthread wd3 = new Soldticketthread ("Window III");
Initiator three threads, which is the window to start selling tickets
Wd1.start ();
Wd2.start ();
Wd3.start ();
}
}

Run Result: (This is because we created 3 threads, each thread has 5 ticket resources, so each thread sells its own 5 tickets, can not achieve resource sharing)

Window two sold a ticket, the remaining 4 tickets
Window one sold a ticket, the remaining 4 tickets
Window one sold a ticket, the remaining 3 tickets
Window one sold a ticket, the remaining 2 tickets
Window one sold a ticket, the remaining 1 tickets
Window one sold a ticket, the remaining 0 tickets
Window two sold a ticket, the remaining 3 tickets
Window two sold a ticket, the remaining 2 tickets
Window two sold a ticket, the remaining 1 tickets
Window two sold a ticket, the remaining 0 tickets
Window three sold a ticket, the remaining 4 tickets
Window three sold a ticket, the remaining 3 tickets
Window three sold a ticket, the remaining 2 tickets
Window three sold a ticket, the remaining 1 tickets
Window three sold a ticket, the remaining 0 tickets

Combining the results above, we can only create a thread to get the shared resources of these 5 tickets

public class Soldticketthread implements Runnable {
private int ticket = 5;

public void Run () {
while (Ticket > 0) {
System.out.println (Thread.CurrentThread (). GetName () + "sold a ticket, remaining" + (--ticket) + "Ticket");
}
}

public static void Main (string[] args) {
To create an object that implements the Runnable interface, get the 5-ticket resources
Soldticketthread window = new Soldticketthread ();
Pass this resource class as a parameter to 3 threads
Thread wd1=new thread (Windows, "window One");
Thread wd2=new Thread (window, "Windows two");
Thread wd3=new thread (Windows, "window three");
Initiator three threads, which is the window to start selling tickets
Wd1.start ();
Wd2.start ();
Wd3.start ();
}
}

Run Result:

Window one sold a ticket, the remaining 4 tickets
Window one sold a ticket, the remaining 2 tickets
Window one sold a ticket, the remaining 1 tickets
Window two sold a ticket, the remaining 3 tickets
Window one sold a ticket, the remaining 0 tickets

If you have to use the way to inherit thread ...

public class Soldticketthread extends Thread {
private int ticket = 5;

public void Run () {
while (Ticket > 0) {
System.out.println (Thread.CurrentThread (). GetName () + "sold a ticket, surplus"
+ (--ticket) + "Ticket");
}
}

public static void Main (string[] args) {
Soldticketthread window = new Soldticketthread ();
Thread wd1 = new thread (Windows, window two);
Thread wd2 = new thread (Windows, window one);
Thread WD3 = new Thread (window, "Windows III");
Wd1.start ();
Wd2.start ();
Wd3.start ();
}
}

Operation Result: Window is random, order of selling ticket is random

Window two sold a ticket, the remaining 4 tickets
Window two sold a ticket, the remaining 1 tickets
Window two sold a ticket, the remaining 0 tickets
Window three sold a ticket, the remaining 2 tickets
Window one sold a ticket, the remaining 3 tickets

Want to let this sell ticket has a order swollen ... , use synchronized to lock the whole contents of the selling operation, so that only once a ticket is sold once. To lock up our resources.


Implement Runnable Interface implementation:

public class Soldticketthread implements Runnable {
private int ticket = 5;
Private synchronized void sale () {
if (Ticket > 0) {
System.out.println (Thread.CurrentThread (). GetName () + "sold a ticket, remaining" + (--ticket) + "Ticket");
try {
Thread.Sleep (100);
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}

public void Run () {
while (Ticket > 0) {
Sale ();
This is to make sure the resources are locked before you go to the Ticket sales section.
}
}

public static void Main (string[] args) {
Soldticketthread window = new Soldticketthread ();
Thread wd1 = new thread (Windows, window two);
Thread wd2 = new thread (Windows, window one);
Thread WD3 = new Thread (window, "Windows III");
Wd1.start ();
Wd2.start ();
Wd3.start ();
}
}

Run Results: (The Line Cheng (window) will be preempted CPU resources, is random)

Window three sold a ticket, the remaining 4 tickets
Window one sold a ticket, the remaining 3 tickets
Window two sold a ticket, the remaining 2 tickets
Window one sold a ticket, the remaining 1 tickets
Window one sold a ticket, the remaining 0 tickets
Inherit Thread class

public class Soldticketthread extends Thread {
private int ticket = 5;

Public synchronized void Sale () {
if (Ticket > 0) {
System.out.println (Thread.CurrentThread (). GetName () + "sold a ticket, surplus"
+ (--ticket) + "Ticket");
}
}

public void Run () {
while (Ticket > 0) {
Sale ();
}
}

public static void Main (string[] args) {
Soldticketthread window = new Soldticketthread ();
Thread wd1 = new thread (Windows, window two);
Thread wd2 = new thread (Windows, window one);
Thread WD3 = new Thread (window, "Windows III");
Wd1.start ();
Wd2.start ();
Wd3.start ();
}
}

Run Result: (window will be preempted CPU resources, is random)

Window three sold a ticket, the remaining 4 tickets
Window one sold a ticket, the remaining 3 tickets
Window one sold a ticket, the remaining 2 tickets
Window one sold a ticket, the remaining 1 tickets
Window one sold a ticket, the remaining 0 tickets

Summary: Because we just created an object with a 5-Ticket thread class (5 train tickets), and then passed the object as a parameter to 3 newly created thread objects, we shared the 5 train tickets. Then we sell the ticket operation plus synchronized operation, you can achieve in order to sell tickets.

The point to keep in mind is that I think the beginner teacher will think that the program is executed from top to bottom, it fits our logic, but the thread can be seen as a concurrent operation, not that you start first, you will run first.


Also to record the point of the daemon thread ... In a DOS environment, Jstack can view the PID that is currently running Java classes, and then enter the Jstack-l PID to see what daemons are currently available ....

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.