1

I am looking at an example which code is:

class SimpleThread extends Thread {
    public SimpleThread(String str) {
        super(str);
}

public void run() {
    for (int i = 0; i < 10; i++) {
        System.out.println(i + " " + getName());
            try {
        sleep((int)(Math.random() * 1000));
        } catch (InterruptedException e) {}
    }
    System.out.println("DONE! " + getName());
    }
}

and

class TwoThreadsTest {
    public static void main (String args[]) {
        new SimpleThread("Jamaica").start();
        new SimpleThread("Fiji").start();
    }
}

My question is: is there a way each thread does its own code? For example, one thread increments a variable, while the other thread increments other variable. Thanks.

P.S. Example's link is: http://www.cs.nccu.edu.tw/~linw/javadoc/tutorial/java/threads/simple.html

bbalchev
  • 827
  • 1
  • 9
  • 19
  • Aren't they already doing that...? – mellamokb Mar 28 '12 at 22:10
  • Well, aren't they both doing that loop? I don't see what separates their tasks. Maybe the following is easier to get my idea: Thread1 does A, B, C Thread2 does D, E, F What I see now is they both execute what is in run(). Sorry, I'm just a beginner. – bbalchev Mar 28 '12 at 22:15
  • They are both doing the loop, but their own copies. So the `i` in thread 1 is completely unrelated to the `i` in thread 2. They are looping and processing independently of each other, even though they are doing essentially the exact same thing. – mellamokb Mar 28 '12 at 22:16
  • Exactly. What I am looking for is they do not do the exact same thing. Is this considered okay or did I misunderstand multithreading? – bbalchev Mar 28 '12 at 22:20
  • 1
    If you want them to do two different things, create two different classes that extend `Thread` and implement the different `run()` methods. Or you can pass a parameter into the thread that defines what it does, say processType = 0 or 1. – mellamokb Mar 28 '12 at 22:31
  • Is the 2nd suggestion alright if all of my code is in the same file? My assignment is really dumb to restrict more than 1 file. You may take a look if you have time: http://uploading.com/files/5e54cddd/Assignment-1.pdf/ – bbalchev Mar 28 '12 at 22:43
  • The assignment only states that you have to use only one file. That doesn't mean you can't have as many classes as you want - they will just all have to be `private` (except `Office`). It also looks like you are allowed to use either a single class to represent the different players in the program, or separate classes, as it's not specified. In this case it would probably be easier to keep track of things if every class was separate. However, these types of questions in the future are probably better asked of your teacher rather than SO. Good luck! – mellamokb Mar 29 '12 at 13:51
  • By the way, the Executors framework added to Java 5 has supplanted using `Thread` class directly. No need to subclass `Thread`. Just pass a `Runnable` or `Callable` to an executor service. – Basil Bourque Dec 26 '20 at 07:33
  • By the way, your example code has a threading problem: `Math.random` has some contention issues when called across threads. Discussed on Question, [*Random over ThreadLocalRandom*](https://stackoverflow.com/q/23396033/642706). Better to use [`ThreadLocalRandom`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ThreadLocalRandom.html) class. This shows just how tricky concurrency work can be. – Basil Bourque Dec 26 '20 at 07:39

2 Answers2

2

Each instance of SimpleThread has it's own local class storage. As long as you aren't using fields marked as static, then each thread will "do its own code". It is much harder to synchronize values between threads.

For example:

class SimpleThread extends Thread {

    // this is local to an _instance_ of SimpleThread
    private long sleepTotal;

    public SimpleThread(String str) {
        super(str);
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i + " " + getName());
            try {
                long toSleep = Math.random() * 1000;
                // add it to our per-thread local total
                sleepTotal += toSleep;
                sleep(toSleep);
            } catch (InterruptedException e) {}
        }
        System.out.println("DONE!  " + getName());
    }
}
Gray
  • 115,027
  • 24
  • 293
  • 354
  • Don't both threads share and execute the same code that is in run()? If yes, isn't it possible that they do different tasks which aren't in the same method run()? E.g. thread1 does A, B,C and thread2 does D and E instead. – bbalchev Mar 28 '12 at 22:36
  • 1
    The share the same _code_ yes @Blagovest but _not_ the same field storage. – Gray Mar 28 '12 at 22:37
  • 2
    @Blagovest If you want them to run different tasks then you can specify a different `run()` method or a different `Thread` class. You could also pass in some value to the constructor and the `run()` method could use it to determine if it should od A,B,C or D,E. – Gray Mar 28 '12 at 22:39
1

Im new to Java and threads myself but you can do something like this (which may not be very efficient) but using an if statement to check the id or getName() of the thread and if it .equals the name of the particular thread then do this etc

so something like this:

int i;
int j;

    if ("thread 2".equals(Thread.currentThread().getName())){
        i++;
        System.out.println("this is thread 2");

        }
    else {
        j++;
        ...
}

This should allow you to make the threads run different tasks under the same run() method

Daveloper87
  • 706
  • 1
  • 8
  • 13