gpt4 book ai didi

java - 我已经编写了一个线程,但如何将其添加到我的 main 方法中?

转载 作者:行者123 更新时间:2023-12-01 13:37:53 24 4
gpt4 key购买 nike

这是我当前的代码;如何编辑 main 方法以使其运行?

import javax.swing.JFrame;


public class Virus {


public static void main(String[] args) {
Thread virus = new Thread();
}
}

class pop implements Runnable
{
public void run()
{
int x = 1000;
int y = 1000;

JFrame popup = new JFrame();
popup.setLocation(x, y);
popup.setVisible(true);

javax.swing.JOptionPane.showMessageDialog(popup, "Virus fun time");
}
}

最佳答案

你已经很接近了。 Runnable 需要一个线程来运行它,并且您将 Runnable 的实例传递到线程中。所以使用Thread(Runnable)构造函数:

Thread virus = new Thread(new pop());

那么你start线程:

virus.start();

然后你需要等待它完成,通过 join :

virus.join();

(您需要处理可能引发的异常。)

This tutorial可能会帮助您了解这些基础知识。

但是,请注意 @MadProgrammer 对这个问题的评论:

Don't modify, change or create UI components outside the Event dispatching thread!

This tutorial可能会帮助你。

关于java - 我已经编写了一个线程,但如何将其添加到我的 main 方法中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21125717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com