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