#Threads101
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
While you are waiting for getting help, here are some tips to improve your experience:
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.
Why should it throw ?
the doc of join doesn't say it would throw if the time runs out. if u expected that
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().
if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
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.
the time to wait in milliseconds
if the value of millis is negative
see, nothing here says it would throw
as u can see, it will only throw if someone interrupts the thread
u never do that
Smh, idk the slides says:
How does that occur? "someone interrupts the thread"
You can call something like Thread.getGroup() and interrupt
Or something like that
Definitely butchered the name
Also, is this wrong? or did I interpret it wrong?
Ah it’s
@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?
Thread.currentThread().getThreadGroup().interrupt()
If you run 2 threads and have one interrupt the group, it will throw this error
public void interrupt()
Interrupts this thread.
Unless the current thread is interrupting itself, which is always permitted, the #checkAccess() method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the #wait(), #wait(long), or wait(long, int)
u just call the interrupt method on the thread u want to interrupt
couldn't be any simpler...
it is wrong. u should get used to consulting the official doc first
I tried calling .interrupt() but for some reason "hi" got printed?
interrupt() does not actually kill the thread
it just sets the interrupted flag
Oh
which the thread can now check with interrupted()
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();
}
}
}
and then maybe use that to stop activity
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
why do u interrupt via the group? u can literally call it on the thread itself
Note that thread group is legacy and shouldn't be used, also most of its methods are deprecated for removal
If you just call Thread.currentThread().interrupt() it won't throw the exception
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
the idea of interrupt is that a flag is set, which the thread can now periodically check and then react to it. for example stop its while(true) loop and do a clean shutdown
If the interrupted statute is set to true, what does that mean? that this thread doesn't mind getting interrupted by other threads?
but some methods adopted this concept to stop a blocking waiting action exceptionally
the thread could now check that flag and react to it
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
ah is this what you meant
@Override
public void run() {
try {
Thread.currentThread().interrupt();
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println(":(");
}
}
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..
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
So it's always best to join the thread where the thread is started? if yes, should I do it before or after the .start() call?
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
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
Waiting for a specific thread to complete
Or terminates
Umm when a new thread is created it will do all its work and then when it terminates, another thread will be created which will do all its work until termination and then 3rd thread will be created...
Yeah exactly
Is that a problem?
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
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
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?
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
join will make the current thread wait until the other thread finishes
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
No for real, isn't that the point of using join? to protect from the race condition? besides using locks/synchronization..
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
no
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
^ Like the code I posted above
how do you make so you wait that all the tasks are over ? by using join
👍🏻 👍🏻 👍🏻 thanks guys