我是Java的新手,正在尝试学习高级并发的概念。我在Java教程Oracle中看到了下面的代码。
但是,当我运行代码时,输出并未指示它来自哪个线程。所以我的问题是,如何输出线程ID(即以某种方式为每个线程分配一个唯一的ID),这样我就可以确定哪个线程正在做什么。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Random;
public class Safelock {
static class Friend {
private final String name;
private final Lock lock = new ReentrantLock();
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public boolean impendingBow(Friend bower) {
Boolean myLock = false;
Boolean yourLock = false;
try {
myLock = lock.tryLock();
yourLock = bower.lock.tryLock();
} finally {
if (! (myLock && yourLock)) {
if (myLock) {
lock.unlock();
}
if (yourLock) {
bower.lock.unlock();
}
}
}
return myLock && yourLock;
}
public void bow(Friend bower) {
if (impendingBow(bower)) {
try {
System.out.format("%s: %s has"
+ " bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
} finally {
lock.unlock();
bower.lock.unlock();
}
} else {
System.out.format("%s: %s started"
+ " to bow to me, but saw that"
+ " I was already bowing to"
+ " him.%n",
this.name, bower.getName());
}
}
public void bowBack(Friend bower) {
System.out.format("%s: %s has" +
" bowed back to me!%n",
this.name, bower.getName());
}
}
static class BowLoop implements Runnable {
private Friend bower;
private Friend bowee;
public BowLoop(Friend bower, Friend bowee) {
this.bower = bower;
this.bowee = bowee;
}
public void run() {
Random random = new Random();
for (;;) {
try {
Thread.sleep(random.nextInt(10));
} catch (InterruptedException e) {}
bowee.bow(bower);
}
}
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new BowLoop(alphonse, gaston)).start();
new Thread(new BowLoop(gaston, alphonse)).start();
}
}
答案 0 :(得分:1)
是的,你可以。使用下面的构造函数来创建一个线程
Thread(Runnable target, String name)
然后你可以通过调用
来打印它的名字Thread.getCurrentThread().getName();
为了生成唯一名称,您可以使用您选择的任何算法。或者如果您想要打印ID,我认为在Thread类中也有方法getId()
。
答案 1 :(得分:1)
您可以使用" Thread.currentThread()。getName()"打印当前线程的名称。所以你的sysout会改为:
System.out.format(Thread.currentThread().getName() + "%s: %s has" +
" bowed back to me!%n",
this.name, bower.getName());
如果您想为线程指定自己的特殊名称,则可以在创建时命名它们:
new Thread(new BowLoop(alphonse, gaston), "MyThread1").start();
new Thread(new BowLoop(gaston, alphonse), "Mythread2").start();**