1

Context:

I am writing a small Java program to troll my friends. This program, when run, spams the screen with many small windows in order to block the view and lag the machine. In an attempt to increase the rate at which windows appear, I've tried creating multiple threads, each one spamming windows on the screen.

Problem and Question:

When I get the state of each thread, only one is runnable and the rest are blocked, causing no increase in the rate of window spam. How can I prevent these threads from becoming blocked?


-Code-


Main class - Creates threads and prints their state after 1 second

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 state output

Thread-0 BLOCKED
Thread-1 BLOCKED
Thread-2 BLOCKED
Thread-3 RUNNABLE

Spam class - Infinitely creates new windows and places them in a random location on the screen

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 class - Each instance instantiates one Spam class

public class MyThread implements Runnable {

    @Override
    public void run() {
        try {
            new Spam();
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}
Ravi
  • 30,829
  • 42
  • 119
  • 173

1 Answers1

0

Thread.BLOCKED

... A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait.

So, once a thread is in WAITING state (waiting for a monitor lock) goes in BLOCK state, and once it acquires monitor then it enters to RUNNABLE state.

Ravi
  • 30,829
  • 42
  • 119
  • 173