gpt4 book ai didi

java - 如何重命名Java的线程

转载 作者:太空宇宙 更新时间:2023-11-04 06:09:02 24 4
gpt4 key购买 nike

这是从 http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/SWTandThread.htm 创建的示例

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;


public class MultiThread extends Shell {

Button btnNewButton = new Button(this, SWT.NONE);

/**
* Launch the application.
* @param args
*/
public static void main(String args[]) {
try {
Display display = Display.getDefault();
MultiThread shell = new MultiThread(display);
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* Create the shell.
* @param display
*/
public MultiThread(Display display) {
super(display, SWT.SHELL_TRIM);


btnNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
applicationThread.start();
}
});
btnNewButton.setBounds(86, 47, 68, 23);
btnNewButton.setText("New Button");
createContents();
}

/**
* Create contents of the shell.
*/
protected void createContents() {
setText("SWT Application");
setSize(450, 300);

}

@Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}


final Runnable print = new Runnable() {
public void run() {
System.out.println("Print from thread: \t" + Thread.currentThread().getName());
}
};

final Thread applicationThread = new Thread("currentThread") {
public void run() {
System.out.println("Hello from thread: \t" + Thread.currentThread().getName());
getDisplay().syncExec(print);
System.out.println("Bye from thread: \t" + Thread.currentThread().getName());
}
};

}

我的问题是:为什么第二次单击按钮时会发生 IllegalThreadStateException?是因为第二次单击创建了一个与上次同名的线程吗?我怎样才能避免这种情况?

提前谢谢您!

最佳答案

使用下面的代码设置线程名称

Thread.currentThread().setName("Hello");

关于java - 如何重命名Java的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28946262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com