2 ways to create JAVA threads __java

Source: Internet
Author: User
Tags extend inheritance thread class ticket
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 overload its run () method;
Implements the Runnalbe interface, overloading the run () method in the Runnalbe interface.



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.

(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 Thread01 {public
    static void main (String []args) {
    	mythread m1=new mythread ("Thread01");
    	Mythread m2=new mythread ("Thread02");
    	M1.start ();
    	M2.start ();
    }

Class Mythread extends thread{
	int tickets=3;
	Mythread (String name) {
		super (name);
	}
	public void Run () {while
		(tickets>0) {
			System.out.println (tickets+ = = = +thread.currentthread (). GetName ());
			tickets--
		}}
	}


Defines a thread class 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.

As you can see from the results, each thread corresponds to 100 movie tickets, there is no relationship between each thread is equal, there is no priority relationship, so have 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 multithreading by implementing Runnable interface



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.

public class Runnable01 {public
     
	static void main (String []args) {
		MyThread2 m1=new MyThread2 ("M1");
		MyThread2 m2=new MyThread2 ("m2");
		Thread T1=new thread (m1);
		Thread t2=new thread (m2);
		T1.start ();
		T2.start ();
	}
Class MyThread2 implements runnable{
	int tickets=3;
	Public  String name;
	MyThread2 (String name) {
		This.name=name
	}
	
	public void Run () {while
		(tickets>0) {
			System.out.println (tickets+ "= =" +name);
			tickets--
		}}
	}



Since 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 the results of the case 4.2.1 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:


Package org.test;

public class Runnable02 {public
     static void main (String []args) {
    	 MyThread5 m=new MyThread5 ();
    	 Thread T1=new thread (m, "T1");
    	 Thread T2=new thread (m, "T2");
    	T1.start ();
    	T2.start ();

     }
Class MyThread5 implements runnable{public
	int i=3;
	
	MyThread5 () {	
	} public
	void Run () {while
		(i>0) {
			System.out.println (i+ "    + Thread.CurrentThread (). GetName ());
			i--
		}}
	}



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, and readers think about why.

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.