0

Can I name this Thread instance? [Solved]

I wanna interrupt this tread later on but I don't know how I can do it. I can't name it anyhow! new Thread(() -> { while (true) { System.out.println("Thread is running"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }).start();

13th Apr 2020, 10:34 PM
Kavoos Salahi
Kavoos Salahi - avatar
6 Answers
+ 3
You just need to use a different constructor with your lambda. https://stackoverflow.com/questions/42975231/naming-thread-within-lambda-expressions
13th Apr 2020, 11:04 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Thank you both a lot. I was frustrated! Thanks.
13th Apr 2020, 11:09 PM
Kavoos Salahi
Kavoos Salahi - avatar
+ 1
I would say you can't. You can't name the tread and while(true) is an infinity loop. I would create an object: Thread t = new Thread();
13th Apr 2020, 10:44 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Maybe this works: Thread myThread = new Thread() -> { //your code }).start();
13th Apr 2020, 11:06 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Despite I've done this a hundred times and see the red line below my code, finally this type of declaration worked. I used to get the error because of .start() method at the end of my code! in this way we have to call the start() method after declaration. Thread t1 = new Thread(() -> { // bunch of code... }); t1.start();
14th Apr 2020, 8:42 PM
Kavoos Salahi
Kavoos Salahi - avatar
0
So how can I put this infinite loop and other stuff in it? Cause I just simplified the contents of while loop.
13th Apr 2020, 10:55 PM
Kavoos Salahi
Kavoos Salahi - avatar