The thread review and summary of Java Learning __java Learning

Source: Internet
Author: User

Java provides thread class thread to create multithreaded programs. In fact, creating a thread is the same as manipulating an object that creates an ordinary class, and a thread is an instance object of the thread class or its subclasses. Each thread object describes a separate threading. There are two ways to produce a thread:

You need to derive a new thread class from the Java.lang.Thread class and override its run () method.
Implements the Runnalbe interface, overloading the run () method in the Runnalbe interface.

The specific steps are as follows:
First, create multithreading by extending (inheriting) the thread class
1, define a class that inherits from thread and rewrite the run () method;
2, create a new instance of the thread subclass, that is, creating the threading object;
3, call the Thread object's start () method to start the thread.
Cases:

Class Mythread extends Thread {//1, defines subclasses of the thread class, public
	void Run () {//and overrides the Thread class's run () method.
		System.out.println (This.getname ());
	}

public class Testthread {public
	static void Main (String args[]) {
		System.out.println (Thread.CurrentThread (). GetName ());
		The CurrentThread () method is a static method of the thread class, which always returns a reference to the currently executing thread object. The
		//GetName () method is an instance method of the thread class that returns the name of the thread that invoked the method.
		mythread thread1 = new Mythread ();//2 creates an instance of a subclass of the thread class that creates the thread object.
		mythread thread2 = new Mythread ();
		Thread1.start ();//3,<span style= "Color:rgb (51, 51, 51); Font-family:verdana, Arial, Helvetica, Sans-serif; font-size:16px; line-height:28px; "> invokes the Start () method of the thread object to start the thread </span>.
		Thread2.start ();
	}

Second, through the implementation of Runnable interface to create multithreading
1, defines a class that implements the Runnable interface and implements the run () method;
2, create a new object of this class (Runnable object);
3, create an object for the thread class and pass in the Runnable object;
4, the Start () method of the Thread class object is invoked to start it.
Cases:

Class Myrunnable implements Runnable {//1, defines a class public
	void Run () {//2) that implements the Runnable interface, and implements the Run () method
		System.out.println (Thread.CurrentThread (). GetName ());
	}

public class Testrunnable {public
	static void Main (String args[]) {
		myrunnable r1 = new myrunnable ();//3, new Runna The object of the BLE class
		myrunnable r2 = new myrunnable ();
		myrunnable R3 = new Myrunnable ();
		Thread thread1 = new Thread (r1, "MyThread1");//4, create a new thread class object and pass in the Runnable class object
		thread thread2 = new Thread (r2);
		Thread2.setname ("MyThread2");
		Thread thread3 = new Thread (r3);
		Thread1.start ();//5, call the Thread class object's Start () method
		Thread2.start ();
		Thread3.start ();
	}

Why does Java provide two ways to create threads? What are the differences between them? Which method is better than that?

In Java, class supports only single inheritance, that is, when a new class is defined, it can only extend an external class. This way, if you create a custom thread class by extending the method of the thread class, the custom class cannot extend the other classes. will not be able to achieve more complex functions. Therefore, if your custom class must extend other classes, you can use a method that implements the Runnable interface to define the class as a thread class, which avoids the limitations of Java single inheritance.

One of the most important is that threads created using the Runnable interface can handle the same resource, thereby sharing resources. About specific Use
(1) to create multithreading by extending the thread class
Suppose a cinema has three ticket outlets, which are used to sell tickets to children, adults and the elderly respectively. The theater has 100 movie tickets for each window, children's, adult and old. Three windows need to sell tickets at the same time, and now there is only one conductor, the conductor is equivalent to a CPU, three Windows is equivalent to three threads. Take a look at how to create these three threads through a program.

public class Mutlithreaddemo {public
    static void Main (String [] args) {
        mutlithread m1=new mutlithread ("Window 1" );
        Mutlithread m2=new mutlithread ("Window 2");
        Mutlithread m3=new mutlithread ("Window 3");
        M1.start ();
        M2.start ();
        M3.start ();
    }
Class Mutlithread extends thread{
    private int ticket=100;//Each thread has 100 tickets
    mutlithread (String name) {
        Super (name),//constructor that invokes the parent class with parameters public
    void Run () {while
        (ticket>0) {
            System.out.println ( Ticket--+ "is saled by" +thread.currentthread (). GetName ());}}

A thread class is defined in a program that extends the thread class. Use the extended thread class to create three thread objects in the main method of the Mutlithreaddemo class and start them separately through the start () method.
You can see from the results that each thread corresponds to 100 movie tickets, and there is no relationship, which means that each thread is equal, has no priority relationship, and therefore has the opportunity to get CPU processing. But the results show that these three threads are not sequentially executed, but in the case of three threads being executed at the same time, some threads are more opportunities to allocate time slices, tickets are sold out in advance, and some threads are allocated time slices less opportunities, the tickets later sold out.
Visible, multiple threads created with the extended thread class, although executing the same code, are independent of each other and have their own resources and do not interfere with each other. (2) Create multithreaded

by implementing the Runnable interface

public class MutliThreadDemo2 {public
    static void Main (String [] args) {
        mutlithread m1=new mutlithread ("Window 1 ");
        Mutlithread m2=new mutlithread ("Window 2");
        Mutlithread m3=new mutlithread ("Window 3");
        Thread T1=new thread (m1);
        Thread t2=new thread (m2);
        Thread t3=new thread (m3);
        T1.start ();
        T2.start ();
        T3.start ();
    }
Class Mutlithread implements runnable{
    private int ticket=100;//Each thread has 100 ticket
    private String name;
    Mutlithread (String name) {
        This.name=name
    }
    public void Run () {while
        (ticket>0) {
            System.out.println (ticket--+ "are saled by" +name);
        }
    }

Because these three threads are independent of each other, each has its own resources, that is, 100 movie tickets, so the results of the program output and (1) results are very similar. are the respective threads of their own 100 tickets for separate processing, do not affect each other.
Visible, as long as the reality of the requirements to ensure that new threads are independent of each other, each have resources, and do not interfere with each other, which way to create multithreading is possible. Because the multithreaded routines created in both of these ways can achieve the same functionality.

(3) Realizing resource sharing among threads by implementing Runnable interface
In reality, such as the simulation of a railway station ticketing system, if the day from A to B of the train ticket only 100 tickets, and allow all windows to sell the 100 tickets, then each window is equivalent to a thread, But the difference between this and the previous example is that all threads are dealing with resources that are the same resource, that is, 100 tickets. It is not possible to create a thread in the previous way, but what to do with it. Look at the following program, the program code looks like this:

public class MutliThreadDemo3 {public
    static void Main (String [] args) {
        mutlithread m=new mutlithread ();
        Thread T1=new thread (M, "Window 1");
        Thread T2=new thread (M, "Window 2");
        Thread T3=new thread (M, "Window 3");
        T1.start ();
        T2.start ();
        T3.start ();
    }
Class Mutlithread implements runnable{
    private int ticket=100;//Each thread has 100 tickets public
    void run () {while
        ( ticket>0) {
            System.out.println (ticket--+ "is saled by" +thread.currentthread (). GetName ())}
        }

The result, as previously analyzed, is that the program creates only one resource in memory, and the new three threads are based on access to the same resource, and because each thread is running the same code, they perform the same function.
As you can see, if a real-world problem requires that multiple threads must be created to perform the same task, and that the same resource will be shared among the multiple threads, a multithreaded program could be created using the implementation of the Runnable interface. This functionality is not achievable by extending the thread class.
The implementation of the Runnable interface has unparalleled advantages over the extended thread class. This approach is not only conducive to the robustness of the program, so that the code can be shared by multiple threads, and the code and data resources are relatively independent, which is particularly suitable for multiple threads with the same code to handle the same resource situation. Thus, the separation of thread, code and data resources effectively embodies the idea of object-oriented programming. As a result, almost all multithreaded programs are accomplished by implementing the Runnable interface.


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.