[英]How do you create multithreading function in java?
My project asked me to create a multithreading function, and it allows up to 1000 threads.我的项目要求我创建一个多线程函数,它最多允许 1000 个线程。 How do you do that in java?
你如何在java中做到这一点?
I know we can do that by implementing the Runnable
interface or creating a subclass to extends Thread
, but I don't know if you can create such a large number of threads.我知道我们可以通过实现
Runnable
接口或创建一个子类来扩展Thread
来做到这一点,但我不知道您是否可以创建如此大量的线程。
try this尝试这个
import java.awt.Component;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class main {
private static JFrame frame;
private static JButton button;
main(){
frame = new JFrame();
button = new JButton("Click");
button.setBounds(20,20,2,2);
button.addActionListener(multi(frame));
frame.setSize(200,200);
frame.add(button);
frame.setVisible(true);
}
public static void main(String[] args) {
new main();
}
private static ActionListener multi (Component GTOS) {
return (ae) -> {
new Thread(() -> {
System.out.println("test");
}).start();
};
}
}
Look at the ExecutorService
.查看
ExecutorService
。 For example, it might look like this:例如,它可能如下所示:
public void myMethod() {
ExecutorService executor = Executors.newFixedThreadPool(1000);
List<Callable<Boolean>> callableList = new ArrayList<Callable<Boolean>>();
// any list for init our threads
for (int i = 0; i < 1000; i++)
callableList.add(() -> exec());
executor.invokeAll(callableList);
}
public boolean exec() {
// do something
return true;
}
This code isn't great for a number of reasons, but it does show you a way to create 1,000 threads:由于多种原因,这段代码并不是很好,但它确实向您展示了一种创建 1,000 个线程的方法:
for (int n = 0; n < 1000; n++) {
new Thread("thread " + n).start();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.