我在我的run方法中嘗試使用getName()和Thread.getName(),但它們不起作用。有什麼建議麼?如何在此代碼中獲得我的java線程的名稱?
我需要獲取該線程所屬的變量名稱。 我是一個初學者程序員,所以任何指導表示讚賞。如果必須,我會解釋更多。
這就是我要說的,我只是添加更多的詞來擺脫煩人的「主要代碼」限制。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ThreadEx extends JFrame
{
JButton btnStart = new JButton("A button");
public ThreadEx()
{
this.setTitle("Threads");
this.setSize(300, 200);
this.setLayout(new GridLayout(0, 1));
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
JProgressBar progressBar1 = new JProgressBar();
JProgressBar progressBar2 = new JProgressBar();
JLabel label1 = new JLabel("Progress 1: ");
JLabel label2 = new JLabel("Progress 2: ");
InnerProgress innerProgress1 = new InnerProgress(label1, progressBar1);
InnerProgress innerProgress2 = new InnerProgress(label2, progressBar2);
Thread t1 = new Thread(innerProgress1);
Thread t2 = new Thread(innerProgress2);
t1.start();
t2.start();
btnStart.addActionListener(clickListener);
this.add(btnStart);
this.add(innerProgress1);
this.add(innerProgress2);
this.pack();
}
public class InnerProgress extends JPanel implements Runnable
{
JLabel label;
JProgressBar progress;
InnerProgress(JLabel _label, JProgressBar _progress)
{
label = _label;
progress = _progress;
this.add(label);
this.add(progress);
}
public void run()
{
System.out.println("Running: "); //<===== This is where I want to add thread name
}
}
獲取當前'Thread'並用'getName()'打印它的名字。 –