Example analysis of executing multiple programs in java multithreading

  • 2021-08-16 23:58:19
  • OfStack

We know that multithreading can achieve high efficiency for program running because of its ability to deal with sub-threads at the same time. However, many people have not tried the execution method of multithreading. In this article, we will introduce the method of creating threads, and on this basis, show the method of executing multiple commands. Let's take a look at the specific operation steps.

1. To create a thread object, we need to use Thread class, which is a class under java. lang package, so there is no need to import the package when calling. Let's create a new subclass to inherit the Thread class, and then override the run () method (writing the tasks that need to be done simultaneously into the run () method) to get the program to do more than one thing at a time.


import java.awt.Graphics;
import java.util.Random;
public class ThreadClass extends Thread{
public Graphics g;
// The canvas is passed into by using the constructor to pass parameters ThreadClass Class 
public ThreadClass(Graphics g){
this.g=g;
}
public void run(){
// Gets the random x,y Coordinates as the coordinates of the ball 
Random ran=new Random();
int x=ran.nextInt(900);
int y=ran.nextInt(900);
for(int i=0;i<100;i++){
g.fillOval(x+i,y+i,30,30);
try{
Thread.sleep(30);
}catch(Exception ef){
}
}
}
}

2. Insert one piece of code on the button event listener side of the main class, that is, one ThreadClass object is generated every time a button is pressed.


public void actionPerformed(ActionEvent e){
ThreadClass thc=new ThreadClass(g);
thc.start();
}

3. Here, after we generate ThreadClass object and call start () function, the thread is created and enters the ready state. Each thread object can independently execute the function in run () method at the same time, and the thread automatically stops when the code in run () method is finished.

Example of java8 multithreaded running program


public class Main {
  //method to print numbers from 1 to 10
  public static void printNumbers() {
    for (int i = 1; i <= 10; i++) {
      System.out.print(i + " ");
    }
    //printing new line
    System.out.println();
  }
 
  //main code	
  public static void main(String[] args) {
    //thread object creation
    Thread one = new Thread(Main::printNumbers);
    Thread two = new Thread(Main::printNumbers);
 
    //starting the threads
    one.start();
    two.start();
  }
}

Output

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10


Related articles: