Java Thread example-inherit the Thread class and implement the Runnable interface

Source: Internet
Author: User
Tags java reference

Process)AndThread)Is the two basic units for running the program. Java concurrent programming is more related to threads.

Process

A process is an independent execution unit and can be considered as a program or application. However, a program's internal colleagues also contain multiple processes. The Java Runtime Environment is a separate process, which also contains various types and programs as processes.

Thread

The thread can be seen as a lightweight process. The thread exists in the process and requires a low resource overhead. Threads in the same process share the resources of the process.

Java Multithreading

For every Java reference, there is only one thread-main thread ). Although many other threads are running in the background, such as memory management, system management, and signal processing, main is the first thread from the application perspective, we can create multiple threads from it.

Advantages of threads

1. Compared with processes, the thread is lightweight, and the time overhead and resource overhead of thread creation are very small.

2. threads of the same process share the data and code of the process.

3. the overhead of context switching between threads is usually less than that of processes.

4. Compared with inter-process communication, inter-thread communication is more convenient.

In programming, Java provides two ways to create threads:

1. Implement the java. lang. Runnable interface

2. inherit the java. lang. Thread class

Java thread example-implement the Runnable interface

To make the class run, we need to implement the java. lang. Runnable interface, andPublic void run ()Method. At the same time, you also need to create a Thread object and break in the class that implements the Runnable interface as a parameter so that you can callStart ()Run in an independent threadRun ().

The following is a Java class that implements the Runnable interface.

HeavyWorkRunnable. java

package com.journaldev.threads;public class HeavyWorkRunnable implements Runnable {    @Override    public void run() {        System.out.println("Doing heavy processing - START " + Thread.currentThread().getName());        try {            Thread.sleep(1000);            //Get database connection, delete unused data from DB            doDBProcessing();        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println("Doing heavy processing - END " + Thread.currentThread().getName());    }    private void doDBProcessing() throws InterruptedException {        Thread.sleep(5000);    }}
Java Thread example-inherit the Thread class

You can integrate the java. lang. Thread class and rewrite it.Run ()Method to create your own Thread class. We can create a thread Class Object and callStart ()To execute the defined run method.

The following example demonstrates how to integrate the Thread class.

MyThread. java

package com.journaldev.threads;public class MyThread extends Thread {    public MyThread(String name) {        super(name);    }    @Override    public void run() {        System.out.println("Doing heavy processing - START " + Thread.currentThread().getName());        try {            Thread.sleep(1000);            //Get database connection, delete unused data from DB            doDBProcessing();        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println("Doing heavy processing - END " + Thread.currentThread().getName());    }    private void doDBProcessing() throws InterruptedException {        Thread.sleep(5000);    }}

The following test program demonstrates how to create and execute a thread.

ThreadRunExample. java

package com.journaldev.threads;public class ThreadRunExample {        public static void main(String[] args) {        Thread t1 = new Thread(new HeavyWorkRunnable(), "t1");        Thread t2 = new Thread(new HeavyWorkRunnable(), "t2");        System.out.println("Starting Runnable threads");        t1.start();        t2.start();        System.out.println("Runnable Threads has been started");        Thread t3 = new MyThread("t3");        Thread t4 = new MyThread("t4");        System.out.println("Starting MyThreads");        t3.start();        t4.start();        System.out.println("MyThreads has been started"):    }}
The output result of the above Java program is as follows:

Starting Runnable threadsRunnable Threads has been startedDoing heavy processing - START t1Doing heavy processing - START t2Starting MyThreadsMyThread - START Thread-0MyThreads has been startedMyThread - START Thread-1Doing heavy processing - END t2MyThread - END Thread-1MyThread - END Thread-0Doing heavy processing - END t1
Once we start the thread, its execution depends on the time slice of the operating system, and we cannot control the thread execution. However, we can set the thread priority, but this cannot ensure that the high-priority thread will give priority to execution.

Compare Runnable and Thread

If your class is not only run as a thread, but needs to provide more functions, you should implement the Runnable interface. If your class is only running as a Thread, You can inherit the Thread class directly.

Compared with inheriting the Thread class, it is better to implement the Runnable interface because Java supports multi-interface implementation. Once your class inherits the Thread class, it will no longer be able to inherit other classes.


TIPS:You may have noticed that the thread does not return any value, but if we want the thread to return the processing result to the client program after processing, we can refer to the article Java Callable Future.


Update:Starting from Java 8, the Runnable agenda has a functional interface in good faith. We can use lambda expressions to implement it, rather than using anonymous classes. For more information, see Java 8 Lambda Expressions Tutorial.





Original article address: Java Thread Example-Extending Thread Class and Implementing Runnable Interface

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.