获取名字和设置名字

获取名字和设置名字

  • 1.获取名字
    • 通过getName()方法获取线程对象的名字
  • 2.设置名字
    • 通过构造函数可以传入String类型的名字

        new Thread("xxx") {
        	public void run() {
        		for(int i = 0; i < 1000; i++) {
        			System.out.println(this.getName() + "....aaaaaaaa");
        		}
        	}
        }.start();
        
        new Thread("yyy") {
        	public void run() {
        		for(int i = 0; i < 1000; i++) {
        			System.out.println(this.getName() + "....bb");
        		}
        	}
        }.start(); 
      
    • 通过setName(String)方法可以设置线程对象的名字

        Thread t1 = new Thread() {
        	public void run() {
        		for(int i = 0; i < 1000; i++) {
        			System.out.println(this.getName() + "....aaaaaaaa");
        		}
        	}
        };
        
        Thread t2 = new Thread() {
        	public void run() {
        		for(int i = 0; i < 1000; i++) {
        			System.out.println(this.getName() + "....bb");
        		}
        	}
        };
        t1.setName("芙蓉姐姐");
        t2.setName("凤姐");
        
        t1.start();
        t2.start();
      
package com.heima.threadmethod;

public class Demo01_Name {

	/**
	 * @param args
	 * 设置名字有两种方式:
	 * 1.构造赋值
	 * 2.set赋值
	 */
	public static void main(String[] args) {
		//demo1();
		Thread t1 = new Thread() {
			public void run() {
				//this.setName("张三");
				System.out.println(this.getName() + "....aaaaaaaaaaaaa");
			}
		};
		
		Thread t2 = new Thread() {
			public void run() {
				//this.setName("李四");
				System.out.println(this.getName() + "....bb");
			}
		};
		
		t1.setName("张三");
		t2.setName("李四");
		t1.start();
		t2.start();
	}

	public static void demo1() {
		new Thread("芙蓉姐姐") {							//通过构造方法给name赋值
			public void run() {
				System.out.println(this.getName() + "....aaaaaaaaa");
			}
		}.start();
		
		new Thread("凤姐") {
			public void run() {
				System.out.println(this.getName() + "....bb");
			}
		}.start();
	}
}
发布了347 篇原创文章 · 获赞 11 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/LeoZuosj/article/details/104184592