线程的创建:
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 void yield()
//获取当前运行的线程引用
static Thread currentThread()
Thread And Runnable 的简单实现
public class Actress implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +" I am an actress");
int count = 0;
boolean keepRunning = true;
while(keepRunning) {
System.out.println(Thread.currentThread().getName()+ " appear "+count++);
System.out.println(Thread.currentThread().getName()+" finish acting");
if(count == 100) {
keepRunning = false;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Actor extends Thread {
public void run() {
System.out.println(getName() +" I am an actor");
int count = 0;
boolean keepRunning = true;
while(keepRunning) {
System.out.println(getName()+ " appear "+count++);
System.out.println(getName()+" finish acting");
if(count == 100) {
keepRunning = false;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread act = new Actor();
act.setName("Mr Thread");
act.start();
Thread actress = new Thread(new Actress(), "MS.Runnable");
actress.start();
}
}