1
public class Main {
    public static void main(String[] args) {
        LinkedList<Th> myThreads = new LinkedList<>();

        for (int i = 0; i < 100; i++) {
            myThreads.add(new Th());
            myThreads.get(i).start();
        }
    }
}

public class Th extends Thread {

    int myInt;

    @Override
    public void run() {
        while(true) {
           doSomething();
        }
    }

    private void doSomething() {
        switch (myInt) {
            case 0: {
               // System.out.println("comment part");
                break;
            }
            case 2:{
                System.out.println("2");
                break;
            }
        }
    }
}

Hi, I have trouble with a simple multithreading in java. when I run this program, cpu usage is suddenly 100% and my computer crashes and I can't stop the program. Here you can see the code. when I un-comment the comment part, everything is ok! but I need to fix this without printing anything in the console. PS. I already know that case 2 codeblock is never compiled.

u32i64
  • 2,384
  • 3
  • 22
  • 36
Sarasr
  • 43
  • 5
  • 2
    What comment part? Also, if you don't tell the CPU to sleep, it won't sleep. – Steve Smith Jul 13 '17 at 11:42
  • we you have an infity loop with `while(true)` – Philipp Sander Jul 13 '17 at 11:44
  • 4
    100 Threads doing an infinite loop... – Davide Spataro Jul 13 '17 at 11:45
  • What are you trying to do ? – bhathiya-perera Jul 13 '17 at 11:45
  • @SteveSmith I just added the comment part, sorry. the program i'm writing does not need the cpu to sleep – Sarasr Jul 13 '17 at 11:46
  • @BhathiyaPerera I'm writing a game in which there are some enemies and Humans etc. and each is a Thread that's what I'm trying to do – Sarasr Jul 13 '17 at 11:47
  • 1
    "the program i'm writing does not need the cpu to sleep" What is the problem then? – Steve Smith Jul 13 '17 at 11:47
  • 1
    in other words, starting 100 Threads, each doing infinite loops of something as fast as possible => the CPU is fully occupied unless having more than about 100 cores. – user85421 Jul 13 '17 at 11:49
  • @Sarasr If there will be 1000 enemies, you would do 1000 threads with infinite loop in each? This won't speed up your game at all. – u32i64 Jul 13 '17 at 11:50
  • @sudo do you think I should just use one thread in my program and handle all of these game entities there? I mean is it bad to have a thread for each entity? – Sarasr Jul 13 '17 at 11:53
  • "is it bad to have a thread for each entity" Yes, definitely. Generally, only use other threads for long running operations, e.g. calculating AI. Loop through your entities in a single thread. – Steve Smith Jul 13 '17 at 11:54
  • @Sarasr Threads introduce a large overhead for your operating system, it needs to manage a lot of stuff for each thread. In general something between 1 and 10 threads will show good results (on a multicore machine). Everything beyond that drastically increases the overhead with only low benefit resulting in an increased running time. Most games just place some stuff like logic, sound, graphic into separate threads. Note that if not doing benchmarks or so, you should **always** add a sleep to the life cycle, at least `Thread.sleep(10)` or so. Else your CPU goes 100% and blocks everything else. – Zabuzard Jul 13 '17 at 12:07
  • 1
    @SteveSmith thank you so much for your information – Sarasr Jul 13 '17 at 12:26
  • @Zabuza Thanks a lot – Sarasr Jul 13 '17 at 12:27

2 Answers2

4

This code has nothing wrong in its own. It's your machine that can't cope with the amount of work you required it to do.

Your code spawn 100 threads which will print something to the standard output (costly operation, since you have to ask the OS to do that) as fast as they can. This is a lot of work even for a modern machine.

Try to give up the CPU voluntarily for a while adding a sleep after you have printed out your message.

switch (myInt) {
            case 0: {
                System.out.println("message");
                Thread.sleep(50);
                break;
            }

Plus, there is nothing wrong in having 100%usage of the CPU. You are simply using the whole computational power available. It is something that is good, especially in scientific computation.

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
1

Add a sleep. Simply call sleep method where the print is. Your CPU should sleep for some milliseconds to avoid consuming it for 100%. In your case the console-io acts as a sleep.

Try reducing the threads and use a round robin method to do the calculations.

Round-robin (RR) is one of the algorithms employed by process and network schedulers in computing. As the term is generally used, time slices (also known as time quanta) are assigned to each process in equal portions and in circular order, handling all processes without priority (also known as cyclic executive). See https://en.wikipedia.org/wiki/Round-robin_scheduling

Suggested Modification:

private void doSomething() {
    switch (myInt) {
        case 0: {
            try {
                sleep(100);
            } catch (InterruptedException e) {
                interrupt();
            }
            break;
        }
        case 2:{
            System.out.println("2");
            break;
        }
    }
}

You should call the interrupt method to re-interrupt the thread. Refer: Why invoke Thread.currentThread.interrupt() when catch any InterruptException?

bhathiya-perera
  • 1,303
  • 14
  • 32