Home > Java > javaTutorial > body text

What are the ways to create threads in Java? Three ways to create threads in Java

不言
Release: 2018-09-25 15:49:14
Original
4192 people have browsed it

What this article brings to you is what are the ways to create threads in Java? The three ways to create threads in Java have certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Inherit Thread class creation

By inheriting Thread and rewriting its run(), the thread executes the task in the run method. The created subclass can execute thread methods by calling the start() method.

By inheriting the thread class implemented by Thread, instance variables of the thread class cannot be shared between multiple threads. (Need to create different Thread objects, naturally not shared)

Example:

/**
 * 通过继承Thread实现线程
 */
public class ThreadTest extends Thread{
  
  private int i = 0 ;

    @Override
    public void run() {
        for(;i<50;i++){
            System.out.println(Thread.currentThread().getName() + " is running " + i );
        }
    }

    public static void main(String[] args) {
        for(int j=0;j<50;j++){if(j=20){
                new ThreadTest().start() ;
                new ThreadTest().start() ;
            }
        }
    }
}
Copy after login

2. Create a thread class through the Runnable interface

This method needs to first define a class to implement the Runnable interface and rewrite the run() method of the interface. This run method is the thread execution body. Then create an object of the Runnable implementation class as the parameter target for creating the Thread object. This Thread object is the real thread object. Thread classes that implement the Runnable interface share resources with each other.

/**
 * 通过实现Runnable接口实现的线程类
 */
public class RunnableTest implements Runnable {
    private int i ;
    @Override
    public void run() {
        for(;i<50;i++){
            System.out.println(Thread.currentThread().getName() + " -- " + i);
        }
    }
    public static void main(String[] args) {
        for(int i=0;i<100;i++){
            System.out.println(Thread.currentThread().getName() + " -- " + i);
            if(i==20){
                RunnableTest runnableTest = new RunnableTest() ;
                new Thread(runnableTest,"线程1").start() ;
                new Thread(runnableTest,"线程2").start() ;
            }
        }
    }
}
Copy after login

3. Use Callable and Future to create threads

It can be seen from inheriting the Thread class and implementing the Runnable interface that the above two None of these methods can have a return value and cannot be declared to throw exceptions. The Callable interface realizes these two points. The Callable interface is like an upgraded version of the Runable interface. The call() method it provides will serve as the execution body of the thread and allows a return value.

But the Callable object cannot be directly used as the target of the Thread object, because the Callable interface is a new interface in Java 5 and is not a sub-interface of the Runnable interface. The solution to this problem is to introduce the Future interface, which can accept the return value of call(). The Future interface is a sub-interface of the Runnable interface and can be used as the target of the Thread object. Moreover, the Future interface provides an implementation class: FutureTask.

FutureTask implements Future interface and Runnable interface and can be used as the target of Thread object.

The relationship is as follows:

 

Example:

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class CallableTest {
    public static void main(String[] args) {
        CallableTest callableTest = new CallableTest() ;
        //因为Callable接口是函数式接口,可以使用Lambda表达式
        FutureTask<Integer> task = new FutureTask<Integer>((Callable<Integer>)()->{
           int i = 0 ;
           for(;i<100;i++){
               System.out.println(Thread.currentThread().getName() + "的循环变量i的值 :" + i);
           }
           return i;
        });
       for(int i=0;i<100;i++){
           System.out.println(Thread.currentThread().getName()+" 的循环变量i : + i");
           if(i==20){
               new Thread(task,"有返回值的线程").start();
           }
       }
       try{
           System.out.println("子线程返回值 : " + task.get());
        }catch (Exception e){
           e.printStackTrace();
        }
    }
}
Copy after login

Summary

Through the above three methods, they can actually be classified into two categories: inheriting classes and implementing interfaces. Compared with inheritance, interface implementation can be more flexible and will not be limited by Java's single inheritance mechanism. And resources can be shared by implementing interfaces, which is suitable for multi-threads processing the same resource. Thread knowledge is rich and complicated, and more details need to be learned and mastered.

The above is the detailed content of What are the ways to create threads in Java? Three ways to create threads in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!