简体   繁体   English

Lambda表达式中的命名线程

[英]Naming Thread within Lambda Expressions

I tried to pass name parameter together with Lambda Expressions, but couldn't make it work. 我尝试将名称参数与Lambda表达式一起传递,但无法使其正常工作。 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? 如果没有,为什么不可能呢?

Yes you have the public Thread(Runnable target, String name) constructor. 是的,您具有public Thread(Runnable target, String name)构造函数。 So you can invoke it with: 因此,您可以使用以下命令调用它:

new Thread(() ->{....},"nameHere").start();

public Thread(Runnable target, String name)

Allocates a new Thread object. 分配一个新的Thread对象。 This constructor has the same effect as Thread (null, target, name) . 该构造函数与Thread (null, target, name)具有相同的作用。

Parameters: 参数:
target - the object whose run method is invoked when this thread is started. target -其对象run方法时,该线程启动时调用。 If null , this thread's run method is invoked. 如果为null ,则调用此线程的run方法。
name - the name of the new thread name新线程的名称

So the order is different (runnable before the name). 因此顺序是不同的(可在名称前运行)。 But I guess that is just a detail? 但是我想那只是一个细节?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM