任何人都可以解释这个Java Thread程序吗?

时间:2013-11-05 13:30:34

标签: java multithreading

public class ThTest3a {
    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                Thread th = new Thread();
                for (int i = 0; i < 10; i++) {
                    System.out.println("Anonym\t" + i + "\t" + th.getName());
                }
            }
        };

        Thread th1 = new Thread(r);     
        Thread th2 = new Thread(r);

        th1.start();
        th2.start();
    }
}

1 个答案:

答案 0 :(得分:1)

Runnable r = new Runnable() {
        public void run() {
            Thread th = new Thread();
            for (int i = 0; i < 10; i++) {
                System.out.println("Anonym\t" + i + "\t" + th.getName());
            }
        }
    };

在上面的代码中,您通过提供 Runnable 接口的未实现方法的实现来创建匿名类。有关java中匿名类的更多信息,请查看here

通过查看代码,您似乎正在尝试在循环中执行当前线程的名称。像这样修改你的运行方法

public void run() {

     for(int i=0;i<10;i++) {

             System.out.println("Anonym\t"+i+"\t"+Thread.currentThread().getName());

     }

Thread.currentThread()返回当前执行线程的实例。