事务系统中未正确显示线程的名称

Name of the thread not being shown properly in transaction system

我创建了一个事务系统,它似乎可以与同步线程完美配合。 但是,我希望在以下情况下(EmilyJohn)显示进行交易的人的姓名,而不是线程编号。

代码如下:

public class SharedAccountDriver {

  static int balance = 400;

  public static void main(String[] args) {
    SharedAccount sa = new SharedAccount(balance);
    SharedAccountClient c1 = new SharedAccountClient(sa, "JOHN");
    SharedAccountClient c2 = new SharedAccountClient(sa, "EMILY");
    double x1 = 1000.00;
    double x2 = -400;

    c1.setTransaction(x1);
    c2.setTransaction(x2);

    Thread t1 = new Thread(c1);
    Thread t2 = new Thread(c2);
    t1.start();
    t2.start();
  }
}

public class SharedAccountClient implements Runnable {
  double transaction;
  SharedAccount sa;
  static String name;

  public SharedAccountClient(SharedAccount sa, String string) {
    // TODO Auto-generated constructor stub
    this.sa = sa;
    name = string;
  }

  public void setTransaction(double transaction) {
    this.transaction = transaction;
  }

  public void run() {
    sa.completeTransaction(transaction, name);

  }
}

public class SharedAccount {
  private double balance;

  public SharedAccount(double initialAmount) {
    balance = initialAmount;
  }

  public synchronized void completeTransaction(double amount, String name) {
    double temp = this.balance + amount;

    if (amount < 0)
      System.out.println(Thread.currentThread().getName() + "Withdrawing: "
          + Math.abs(amount));
    else
      System.out.println(Thread.currentThread().getName() + "Depositing: "
          + amount);

    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      System.out.println("Transaction interrupted.");
    }

    balance = temp;
    System.out.println("Current Balance: " + balance);
  }
}

输出为:

 Thread-0Depositing: 1000.0
 Current Balance: 1400.0
 Thread-1Withdrawing: 400.0
 Current Balance: 1000.0

而不是 Thread-0Thread-1,我想要名字,Emily & John

为什么要使用 Thread.currentThread().getName()?您尚未更改该值(通过使用 Thread.setName() 或使用构造函数 new Thread(runnable, name))。

只需使用您传入的方法参数 name,例如

System.out.println(name + "Withdrawing: " + Math.abs(amount));

顺便说一句,为什么字段 String name 声明为 statically?这意味着每次调用构造函数时它都会改变,因此两个对象将具有相同的 name.

由于Thread.currentThread().getName()return是线程的名字,不是线程中的对象,可以用构造函数代替Thread(Runnable target, String name)

在你的情况下,使用类似的东西:

 Thread t1 = new Thread(c1, c1.getName());
 Thread t2 = new Thread(c2, c2.getName());