【发布时间】:2018-01-27 06:10:43
【问题描述】:
上下文:
我正在编写一个小型 Java 程序来欺骗我的朋友。该程序在运行时会在屏幕上显示许多小窗口,以阻塞视图并延迟机器。为了提高窗口出现的频率,我尝试创建多个线程,每个线程都在屏幕上发送垃圾邮件。
问题和疑问:
当我得到每个线程的状态时,只有一个是可运行的,其余的都是阻塞的,导致窗口垃圾邮件率没有增加。如何防止这些线程被阻塞?
-代码-
主类 - 创建线程并在 1 秒后打印它们的状态
public class Init {
public static void main(String[] args) throws InterruptedException {
ArrayList<Thread> list = new ArrayList();
for(int i = 0; i < 4; i++) {
Thread t = new Thread(new MyThread());
t.start();
list.add(t);
}
//Print each Thread's name and state after 1 second
Thread.sleep(1000);
for(Thread t : list) {
System.out.println(t.getName() + " " + t.getState());
}
}
}
线程状态输出
Thread-0 BLOCKED
Thread-1 BLOCKED
Thread-2 BLOCKED
Thread-3 RUNNABLE
垃圾邮件类 - 无限创建新窗口并将它们放置在屏幕上的随机位置
public class Spam {
JFrame window;
Random r;
Dimension screenSize;
int x;
int y;
public Spam() {
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
r = new Random();
while(true) {
x = r.nextInt((int)screenSize.getWidth());
y = r.nextInt((int)screenSize.getHeight());
x -= 100;
y -= 100;
window = new JFrame();
window.setSize(100, 100);
window.setLocation(x, y);
window.setBackground(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256))); //set window to random color
window.setVisible(true);
}
}
}
Thread 类 - 每个实例实例化一个 Spam 类
public class MyThread implements Runnable {
@Override
public void run() {
try {
new Spam();
}
catch(Exception e) {
System.out.println(e);
}
}
}
【问题讨论】:
-
JFrame 不是线程安全的,只能从 EDT 创建
-
@Ferrybig - 谢谢,这可能是我问题的根源。我会进一步调查。
标签: java multithreading thread-state blocked-threads