Home  >  Article  >  Java  >  Java multithreading: How to execute multiple programs at the same time?

Java multithreading: How to execute multiple programs at the same time?

WBOY
WBOYforward
2023-04-21 19:37:201836browse

1. To create a thread object, we need to use the Thread class. This class is a class under the java.lang package, so there is no need to import the package when calling. Next, we first create a new subclass to inherit the Thread class, and then override the run() method (write the tasks that need to be performed simultaneously into the run() method) to achieve the purpose of letting the program do multiple things at the same time.

import java.awt.Graphics;
import java.util.Random;
 
public class ThreadClass extends Thread{
public Graphics g;
//用构造器传参的办法将画布传入ThreadClass类中
public ThreadClass(Graphics g){
this.g=g;
}
public void run(){
//获取随机的x,y坐标作为小球的坐标
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. In the button event listener of the main class, insert a piece of code that generates a ThreadClass object every time the button is pressed.

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

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

The above is the detailed content of Java multithreading: How to execute multiple programs at the same time?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete