Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-04-21 19:37:20
forward
1895 people have browsed it

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){
}
}
}
}
Copy after login

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();
}
Copy after login

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!

Related labels:
source:yisu.com
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