java 大道至简--多线程(6)

java 大道至简--多线程(6)

内容目录:

Thread类函数详解

正文:

Static Void seep(long millis) -- 让线程以指定的毫秒数暂停

Static void sleep(long millis , int naos) -- 让线程以指定的毫秒数加上指定的纳秒数暂停

例子:

package com.redis.chat;

 

public class Hello{

public static void main(String[] args) {

Thread thread = new SunWuKong();

thread.start();

}

}

class SunWuKong extends Thread{

 

@Override

public void run() {

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

System.out.println(i);

try {

Thread.sleep(1*1000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

结果:

每隔一秒会打印一个数字

   

 

Satatic Void yiled()-- 暂停指定线程

例子:

package com.redis.chat;

 

public class Hello{

public static void main(String[] args) {

new SunWuKong("Thrad1");

new SunWuKong("Thrad2");

new SunWuKong("Thrad3");

}

}

class SunWuKong implements Runnable{

 

 Thread t;

 

 SunWuKong(String str) {

      t = new Thread(this, str);

      t.start();

   }

@Override

public void run() {

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

            if ((i % 5) == 0) {

               System.out.println(Thread.currentThread().getName());

               Thread.yield();

            }

      }

      System.out.println(Thread.currentThread().getName());

}

}

 

 

Void join()-- 等待线程死亡

Void join(long millis)-- 在指定的毫秒时间内等待线程死亡


Void join(long millis , int nanos)-- 在指定的毫秒时间加上纳秒时间内等待线程死亡

 

例子:

package com.redis.chat;

 

public class Hello{

public static void main(String[] args) {

Thread t = new Thread(new SunWuKong());

      t.start();

      try {

t.join(2000);

 System.out.println("after waiting for 2000 milliseconds...");

      System.out.print(t.getName());

      System.out.println(", status = " + t.isAlive());

} catch (InterruptedException e) {

e.printStackTrace();

}

     

}

}

class SunWuKong implements Runnable{

 

@Override

public void run() {

Thread t = Thread.currentThread();

      System.out.print(t.getName());

      System.out.println(", status = " + t.isAlive());

}

}

 

结果:

Thread-0, status = true

after waiting for 2000 milliseconds...

Thread-0, status = false

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值