简体   繁体   中英

How do I get the name of my java threads in this code?

I tried using getName() and Thread.getName() in my run method but they will not work. Any suggestions?

I need to get the variable name that the thread belongs to. I am a beginner programmer so any guidance is appreciated. I will explain more if I have to.

This is all I have to say, I am just adding more words to get rid of the annoying "mostly code" restriction.

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  
  }

 }

如下使用,返回当前线程的名称

System.out.println("Running: " + Thread.currentThread().getName());

Thread.currentThread() gives current reference to executing thread.

for(int i=0; i<100; i++){
    progress.setValue(i);
    progress.setString(Thread.currentThread().getName()+" - "+i+"%");
    try {
        Thread.sleep(500);
    } catch (InterruptedException ignore) { }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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