Tummomoxie
Tummomoxie

Reputation: 143

Naming Thread within Lambda Expressions

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

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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 as Thread (null, target, name).

Parameters:
   target - the object whose run method is invoked when this thread is started. If null, this thread's run 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

Related Questions