java线程Thread的常用方法

1.当有很多线程在执行的时候,我们怎么去区分这些线程呢?

        此时需要使用Thread的常用方法:getName(),setName(),currentThread()等

package com.my;

//定义个一个线程,进程Thread
public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            System.out.println(Thread.currentThread().getName()+"线程");
        }
    }
}
package com.my;

public class Test {
    public static void main(String[] args) {

        //new一个线程 使用setName进行起名字
        //
        Thread te1 = new MyThread();
        te1.setName("一号");
        te1.start();



        Thread te2 = new MyThread();
        te2.setName("二号");
        te2.start();

        //使用Thread.currentThread().getName()获取线程名字
        for (int i = 0; i < 50; i++) {
            System.out.println(Thread.currentThread().getName()+"线程");
        }


    }
}

使用构造方法给线程起名字:

package com.my;

//定义个一个线程,进程Thread
public class MyThread extends Thread {
    //使用构造方法进行给线程取名字
    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            System.out.println(Thread.currentThread().getName()+"线程");
        }
    }
}

package com.my;

public class Test {
    public static void main(String[] args) {


        //使用构造器给线程起名字
        Thread te1 = new MyThread("一号");
        te1.start();


        Thread te2 = new MyThread("二号");
        te2.start();

        //使用Thread.currentThread().getName()获取线程名字
        for (int i = 0; i < 50; i++) {
            System.out.println(Thread.currentThread().getName()+"线程");
        }


    }
}

Runnable怎么给线程起名字?

直接使用Thread有参构造器起名字。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值