Home > Java > javaTutorial > Share three ways to build multi-threading in Java

Share three ways to build multi-threading in Java

黄舟
Release: 2017-09-18 09:37:35
Original
1397 people have browsed it

This article mainly introduces relevant information about the three construction methods of java multi-threading. Here are three implementation methods. I hope everyone can master the very important basic knowledge. Friends in need can refer to it

java Three construction methods of multi-threading

Inherit the Thread class to create a thread class


##

public class Thread extends Object implements Runnable
Copy after login

  1. Define a subclass of the Thread class and override its run() method

  2. Create an instance of the Thread subclass, that is, create a thread object

  3. Call the start() method of the thread object to start the thread



public class FirstThread extends Thread {
  public void run(){
    for(int i=0;i<100;i++){
      /*
       * Thread类已经继承了Object
       * Object类创建了name选项 并且有其getName(),setName()方法
       * 在继承Thread的类里面使用时只需要用this引用
      */
      System.out.println(this.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){
        new FirstThread().start();
        new FirstThread().start();
      }
    }
  }

}
Copy after login

The Thread class has inherited Object


The Object class creates the name option and has its getName(), setName() methods


When used in a class that inherits Thread, you only need to use this reference

The above two secondary threads and the main thread are randomly switched, and because the class that inherits Thread is used, the two secondary threads cannot share resources

The start() method does not execute multi-threading immediately after calling it. code, but makes the thread programming runnable state. When to run is determined by the operating system

Implement the Runnable interface to create a thread class


public Thread() 
public Thread(Runnable target) 
public Thread(Runnable target,String name)
Copy after login

  • Define the implementation class of the Runnable interface and override the run() method of the interface

  • Create the Runnable implementation class instance, and use this as the target of Thread to create a Thread object. This Thread object is the real thread object.



public class SecondThread implements Runnable {
  public void run(){
    for(int i=0;i<100;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){
        SecondThread st=new SecondThread();
        //通过new Thread(target,name)创建线程
        new Thread(st,"新线程1").start();
        new Thread(st,"新线程2").start();
      }
    }
  }
}
Copy after login

The above result is that the two secondary threads and the main thread switch randomly, but there is no shared resource because they have no ability to resources for sharing.

After the start() method is called, the multi-threaded code is not executed immediately, but the thread programming is made runnable. When to run is determined by the operating system Inherit the Thread class and create Detailed explanation of shared resources of Runnable interface

When there are only resources that can be shared, the same instantiation object is used. The two creation methods will differ only when they share resources, otherwise they will not share resources. Shared resources are usually modified with the private static modifier.


class Thread1 extends Thread{ 
  private int count=5; 
  private String name; 
  public Thread1(String name) { 
    this.name=name; 
  } 
  public void run() { 
    for (int i = 0; i < 5; i++) { 
      System.out.println(name + "运行 count= " + count--); 
      try { 
        sleep((int) Math.random() * 10); 
      } catch (InterruptedException e) { 
        e.printStackTrace(); 
      } 
    } 

  } 
} 

public class Main { 

  public static void main(String[] args) { 
    Thread1 mTh1=new Thread1("A"); 
    Thread1 mTh2=new Thread1("B"); 
    mTh1.start(); 
    mTh2.start(); 

  } 

}
Copy after login


B运行 count= 5 
A运行 count= 5 
B运行 count= 4 
B运行 count= 3 
B运行 count= 2 
B运行 count= 1 
A运行 count= 4 
A运行 count= 3 
A运行 count= 2 
A运行 count= 1
Copy after login

It is precisely because of the private int count=5; sentence that we have shared resources, but this is the inheritance of the Thread class Subclasses cannot share resources


class Thread2 implements Runnable{ 
  private int count=15; 
  public void run() { 
     for (int i = 0; i < 5; i++) { 
       System.out.println(Thread.currentThread().getName() + "运行 count= " + count--); 
        try { 
          Thread.sleep((int) Math.random() * 10); 
        } catch (InterruptedException e) { 
          e.printStackTrace(); 
        } 
      } 

  } 

} 
public class Main { 

  public static void main(String[] args) { 

    Thread2 my = new Thread2(); 
      new Thread(my, "C").start();//同一个mt,但是在Thread中就不可以,如果用同一个实例化对象mt,就会出现异常   
      new Thread(my, "D").start(); 
      new Thread(my, "E").start(); 
  } 

}
Copy after login


C运行 count= 15 
D运行 count= 14 
E运行 count= 13 
D运行 count= 12 
D运行 count= 10 
D运行 count= 9 
D运行 count= 8 
C运行 count= 11 
E运行 count= 12 
C运行 count= 7 
E运行 count= 6 
C运行 count= 5 
E运行 count= 4 
C运行 count= 3 
E运行 count= 2
Copy after login

The same is true because of the common instance of private int count=15 Objects, only classes that implement Runnable can share resources

So why do subclasses that inherit the Thread class and implement the Runable interface differ when sharing resources?


Because Java can only support single inheritance, the single inheritance feature means that only one subclass can inherit and the Runnabl interface can be followed by many classes, so that multiple threads can share a resource. Operation


Use Callable and Future to create threads

Callable looks like an enhanced version of the Runnable interface. Callable has a call() method that is equivalent to Runnable run() method, but its function is more powerful:

The call() method can have a return value

The call() method can declare that it throws an exception

The Callable interface has Generic restrictions, the generic parameter type in the Callable interface is the same as the return value type of the call() method. Moreover, the Callable interface is a functional interface, so you can use Lambda expressions to create Callable objects. The Runnable interface is also a functional interface, so you can also use Lambda expressions to create Runnable objects.

  1. Create an implementation class of the Callable interface and implement the call() method. The call() method will be used as the thread execution body, and then create an instance of the Callable implementation class.

  2. Use the FutureTask class to Wrapping the Callable object, the FutureTask object encapsulates the call() method of the Callable object

  3. Use the FutureTask class object as the target of the Thread object to create and start a new thread

  4. Call the get() method of the FutureTask object to obtain the return value after the child thread ends


##

public class ThirdThread implements Callable<Integer> {
  public Integer call(){
    int i=0;
    for(;i<100;i++){
      System.out.println(Thread.currentThread().getName()+" "+i);
    }
    return i;
  }

  public static void main(String[] args){
    ThirdThread tt=new ThirdThread();
    FutureTask<Integer> task=new FutureTask<>(tt);
    Thread t=new Thread(task,"有返回值的线程");
    for(int i=0;i<100;i++){
      System.out.println(Thread.currentThread().getName()+" "+i);
      if(i==20){
        t.start();
      }
    }
    try{
      System.out.println("返回值是:"+task.get());
    }catch(Exception e){
      e.printStackTrace();
    }
  }
}
Copy after login

Threads created using Callable and Future of Lambda expressions

public class ThirdThread{
  public static void main(String[] args){
    ThirdThread tt=new ThirdThread();
    //先使用Lambda表达式创建Callable<Integer>对象
    //使用FutureTask封装Callable对象
    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

The above is the detailed content of Share three ways to build multi-threading 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