线程的创建:
Thread()
Thread(String name)
Thread(Runnable target)
Thread(Runnable target,String name)
线程的方法:
启动线程
void start()
线程休眠
static void sleep(long millis)
static void sleep(long millis,int nanos )
使其他线程等待当前线程终止
void join()
void join(long millis)
void join(long millis ,int nanos)
当前运行线程释放处理器资源
获取线程的引用static Thread currentThread() 返回当前运行的线程引用
static void yield()
两种实现方式:
extends Thread
implements Runnable
两种实现方式的区别:
在程序开发中只要是多线程肯定永远以实现Runnable接口为主,因为实现Runnable接口相比继承Thread类有如下好处:
避免点继承的局限,一个类可以继承多个接口。
适合于资源的共享
Runnable接口和Thread之间的联系:
public class Thread extends Object implements Runnable
Thread类也是Runnable接口的子类
package com.imooc.thread;
public class Actor extends Thread {
public void run() {
String name = getName();
System.out.println(name + "是一个演员!");
int count = 0;
boolean keeprunning = true;
while (keeprunning) {
System.out.println(name + "总共演出了" + ++count + "次");
if (count == 100) {
keeprunning = false;
}
if (count % 10 == 0) {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(name + "演出结束!");
}
public static void main(String[] args) {
Thread actor = new Actor();
actor.setName("Mr.Thread");
actor.start();
Thread gactor = new Thread(new GActor(), "Mr.Runnable");
gactor.start();
}
}
class GActor implements Runnable {
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + "是一个演员");
int count = 0;
boolean keeprunning = true;
while (keeprunning) {
System.out.println(name + "总共演出了" + ++count + "次");
if (count == 100) {
keeprunning = false;
}
if (count % 10 == 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(name+"演出结束了!");
}
}