Reputation: 143
I tried to pass name parameter together with Lambda Expressions, but couldn't make it work. The way I solved it is like that:
Thread t1 = new Thread(() ->{
try {
Desktop.getDesktop().browse(new URI("http://www.google.com"));
}catch (IOException e){
e.printStackTrace();
}catch (URISyntaxException e){
e.printStackTrace();
}
}
);
t1.setName("Internet Browser");
t1.start();
Is there way? i could write it within a single line
new Thread("nameHere",() ->{....}).start();
if not, why isn't it possible?
Upvotes: 2
Views: 2102
Reputation: 476967
Yes you have the public Thread(Runnable target, String name)
constructor. So you can invoke it with:
new Thread(() ->{....},"nameHere").start();
public Thread(Runnable target, String name)
Allocates a new
Thread
object. This constructor has the same effect asThread (null, target, name)
.Parameters:
target
- the object whoserun
method is invoked when this thread is started. Ifnull
, this thread'srun
method is invoked.
name
- the name of the new thread
So the order is different (runnable before the name). But I guess that is just a detail?
Upvotes: 9