#Threads101

1 messages · Page 1 of 1 (latest)

granite fiber
#

How come this code doesn't throw InterruptedException?? it should throw the exception but it

vagrant saddleBOT
#

<@&987246399047479336> please have a look, thanks.

vagrant saddleBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

granite fiber
minor sigil
#

the doc of join doesn't say it would throw if the time runs out. if u expected that

tough shuttleBOT
#
public final void join(long millis) throws InterruptedException

Waits at most millis milliseconds for this thread to terminate. A timeout of 0 means to wait forever. This method returns immediately, without waiting, if the thread has not been #start().

throws InterruptedException

if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

implNote

For platform threads, the implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

param millis

the time to wait in milliseconds

throws IllegalArgumentException

if the value of millis is negative

minor sigil
#

see, nothing here says it would throw

#

as u can see, it will only throw if someone interrupts the thread

#

u never do that

granite fiber
#

Smh, idk the slides says:

granite fiber
graceful cedar
#

You can call something like Thread.getGroup() and interrupt

#

Or something like that

#

Definitely butchered the name

granite fiber
graceful cedar
#

Ah it’s

granite fiber
#

@graceful cedar But usually with interruption we don't use that in code, it's based on the OS when it wants to interrupt running threads?

graceful cedar
#

Thread.currentThread().getThreadGroup().interrupt()

#

If you run 2 threads and have one interrupt the group, it will throw this error

tough shuttleBOT
minor sigil
#

u just call the interrupt method on the thread u want to interrupt

#

couldn't be any simpler...

minor sigil
granite fiber
graceful cedar
#

interrupt() does not actually kill the thread

minor sigil
#

it just sets the interrupted flag

granite fiber
#

Oh

minor sigil
#

which the thread can now check with interrupted()

graceful cedar
#
public class Main implements Runnable{
    public static void main(String[] args) throws InterruptedException {
        for(int i = 0; i < 2; i++){
            Thread thread = new Thread(new Main());
            thread.start();
            Thread.sleep(1);
        }
    }

    @Override
    public void run() {
        for(int i = 0; i < 100; i++){
            System.out.println("hey");
            Thread.currentThread().getThreadGroup().interrupt();
        }
    }
}

minor sigil
#

and then maybe use that to stop activity

graceful cedar
#

oh it's so bad

#

sorry let me edit

minor sigil
#

some methods like sleep will throw the exception if interrupted in the meantime

#

or join

#

but other than those, interrupting itself just sets a flag

minor sigil
sweet mural
graceful cedar
#

If you just call Thread.currentThread().interrupt() it won't throw the exception

sweet mural
#

No

#

That's unrelated

#

It will only throw an exception the next time you do a sleep of any kind

#

I use it the Jshell backend project if you want to see an use case

minor sigil
granite fiber
#

If the interrupted statute is set to true, what does that mean? that this thread doesn't mind getting interrupted by other threads?

minor sigil
#

but some methods adopted this concept to stop a blocking waiting action exceptionally

minor sigil
#

how u use that concept is totally up to u

#

methods like sleep or join use it to stop that action

#

there is no magic here. those methods literally have if (interrupted) throw coded into some loop

graceful cedar
#
    @Override
    public void run() {
        try {
            Thread.currentThread().interrupt();
            Thread.sleep(10);
        } catch (InterruptedException e) {
            System.out.println(":(");
        }
    }
granite fiber
#

Do I place join method before the start method or vice versa?

#

What do most ppl do?

#

I figured I should always have the join before the start.. but idk if that's how am supposed to do it or not..

#

^ on the main method

#

If I placed .join() inside the run method, it's literally giving me an infinite loop..

graceful cedar
#

I'm pretty sure the reason for this

#

is that you are joining your thread inside the run

#

which will just wait until that thread is finished

#

which it never finishes because it's waiting

granite fiber
minor sigil
#

if u join after starting, ur rendering threads pointless

#

the purpose of a thread is to compute sth while u can do sth else

#

if u literally wait on it, u didn't gain anything

graceful cedar
#

Yeah, do you understand the purpose of join()?

#
List<Thread> threads = new ArrayList<>();
for(int i = 0; i < 3; i++){
    Thread thread = new Thread(new Main());
    threads.add(thread);
    thread.start();
    thread.join();
}
#

Let's say we have this dumby code

granite fiber
#

Or terminates

graceful cedar
#

Looking at the code I just posted

#

what do you think the problem is?

granite fiber
graceful cedar
#

Yeah exactly

granite fiber
#

Is that a problem?

graceful cedar
#

So what Zab said, it pretty much negates the purpose of creating threads

#

I created three threads, but really only getting the performance of one thread

granite fiber
#

Right

#

So what's the point of using join?

graceful cedar
#

Zab might chew me out on this

#

but

#

Let's say you need the completion of the thread parts done before moving on

#
public static void main(String[] args){
    List<Thread> threads = new ArrayList<>();
    for(int i = 0; i < 3; i++){
        Thread thread = new Thread(new Main());
        threads.add(thread);
        thread.start();
    }
    threads.forEach(x -> {
        try {
            x.join();
        } catch (InterruptedException e) {
            System.out.println(":(");
        }
    });
}
#

this allows each thread to be created and ran

#

but it won't continue main, as it will wait for each thread to finish

#

So let's say you have a 1000x1000 matrix, (pretty big)

#

You create 4 threads to handle traversing the matrix, giving each thread a quarter of the matrix for calculation purposes

#

This solution allows each thread to run at the same time

#

If you call join() like the previous example, each thread is not doing calculations at the same time

granite fiber
#

So can I say the idea of using join(), is to prevent the interference of more than one thread on the same data that they share, so that I don't get inaccurate results?

graceful cedar
#

There are some cases like the above code that I posted in which join() is beneficial, but I wouldn't say it is to protect race cases or whatever

#

I'm not an expert on threads so maybe someone else can chime in, but if you are using join() such that each thread takes a turn, and not running it together, the results will not be faster

#

In that case, you might as well only have one thread

sweet mural
graceful cedar
#

There are better ways to prevent accessing the same data such as locks or semaphores or whatever, but I am pretty sure that stuff is outdated

granite fiber
graceful cedar
#

For multithreading, if you are sharing data, you want the critical part of the code to be the least. If you are using join, the entire code is the critical zone

sweet mural
#

join is useful because you usually have a master thread

#

and you want to process stuff in parallel

#

and then once all of them are over, collect the result

graceful cedar
#

^ Like the code I posted above

sweet mural
#

how do you make so you wait that all the tasks are over ? by using join

granite fiber