java线程中常用的方法

class Student {
    public static void main(String[] args) {
       Mythread mythread=new Mythread();
       Thread t2=new Thread(mythread);
       t2.start();
       
       
    }
    
    
    
    
}

class Mythread implements Runnable {
    @Override
    public void run() {
        Thread t1 = Thread.currentThread();//获取当前线程对象 ,调用Thread的grt方法
        System.out.println("线程id为"+t1.getId()+"     线程名字为:"+t1.getName() + "    hello word");//Thread类中有getName方法

    }
}

sleep方法实现时钟计时效果

import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo8 {
    public static void main(String[] args)  {
       mmm myThread = new mmm();
        Thread thread = new Thread(myThread);
        thread.start();

    }
}

class mmm implements Runnable {

    @Override
    public void run() {
        while (true) {
            Date d1 = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    System.out.println(sdf.format(System.currentTimeMillis()));
            System.out.println(sdf.format(d1));
            try {
                Thread.currentThread(). sleep(1000);//Thread.currentThread()获取当前线程
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}

setDemao实现守护线程

public class DemoDaemon {
    public static void main(String[] args) {
        thread t=new thread();
        t.setDaemon(true);//守护线程必须在start之前调用
        t.start();
        System.out.println("==============");
        for (int i = 0; i < 10; i++) {
            System.out.println("主线程             "+i);
        }
    }
}
class   thread extends Thread{
    @Override
    public void run() {
      //  System.out.println( isDaemon()?"是守护线程":"不是守护线程");默认不是守护线程

        for (int i = 0; i < 30; i++) {
            System.out.println("子线程"+i);
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值