【问题标题】:How to Restore Thread from Blocked to Runnable State?如何将线程从阻塞状态恢复为可运行状态?
【发布时间】: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


【解决方案1】:

Thread.BLOCKED

... 一个线程 处于阻塞状态的是等待监视器锁定进入 同步块/方法或在之后重新输入同步块/方法 打电话给Object.wait

因此,一旦线程处于WAITING 状态(等待监视器锁定),就会进入BLOCK 状态,一旦它获得监视器,它就会进入RUNNABLE 状态。

【讨论】:

    猜你喜欢
    • 2016-04-25
    • 2013-11-27
    • 2015-07-10
    • 2016-07-06
    • 2016-05-27
    • 2015-03-08
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    相关资源
    最近更新 更多