A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 谢毅 中级黑马   /  2013-1-21 19:13  /  1470 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 张向辉 于 2013-1-22 12:58 编辑

System.out.println(Thread.currentThread().getName()+"消费-----"+name);
System.out.println(this.getName()+"消费-----"+name);

两个打印线程名字的方式有什么区别,这里需要注意什么?

6 个回复

倒序浏览
一个是打印此时线程中的线程名,另一个则是打印对象中的getname()方法
回复 使用道具 举报
public class Test {

        /**
         * @param args
         */
        public static void main(String[] args) {
                // TODO Auto-generated method stub
                new Thread(new Runnable(){
                        @Override
                        public void run() {
                                while(true){
                                        System.out.println(Thread.currentThread().getName()+"---Runnable");
                                        //System.out.println(this==Thread.currentThread());这句话会编译失败
                                }
                        }
                }).start();
                new Thread(){
                        public void run() {
                                while(true){
                                        System.out.println(Thread.currentThread().getName()+"--------Thread");
                                        System.out.println((this==Thread.currentThread())+"--------Thread");
                                }
                        };
                }.start();
                while(true){
                        System.out.println(Thread.currentThread().getName()+"--------Thread");
                        //System.out.println(this.getName()+"--------main");
                        //System.out.println(this==Thread.currentThread());这两句话同样会编译失败
                }
        }

}
从上面可以看出,使用Thread.currentThread().getName()和使用this.getName();都可以得到线程的名称
但是使用this有局限性。使用this调用getName();方法只有在Thread的子类中才行,在Runnable接口中或其他类中
this都不能调用,因为this代表的是所在的类,只能使用Thread.currentThread().getName()获取线程的名称。
如果编译(this==Thread.currentThread())会出现编译时异常。

评分

参与人数 1技术分 +1 收起 理由
黄锦成 + 1 赞一个!

查看全部评分

回复 使用道具 举报
多线程中 貌似没有用this.getName()获取多线程名字的方法啊?this.方法名,是为了获取当前对象的方法。多线程中获取线程名称的方法是:Thread.currentThread().getName()
回复 使用道具 举报
貌似张孝祥还说,我们在开发时 千万别这么用哦~~
回复 使用道具 举报
Thread.currentThread():获取当前执行线程,getName()获取他的名字
this.getName()获取本类对象的名字
回复 使用道具 举报
使用Runnable方式实现线程,使用第一种方式
如果通过继承Thread方式实现多线程,两种都可以。第二种方式,this就表示运行中的线程
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马