1。Thread类和Runnable接口
2。主线程:用Thread的static Thread currentThread()方法获得
3。通过实现Runnable接口创建线程:实现Runnable接口的run方法。新线程在run()方法返回时结束。注意用这种方法创建进程时,在实现Runnable接口的类的构造函数里通常需要用new Thread新建一个线程,并用start函数开启这个线程。实质上,start函数执行的就是对run函数的调用。如:
class DemoThread implements Runnable{
Thread t;
static int ThreadNum = 1;
public DemoThread() throws Exception{
t = new Thread(this, "Demo Thread");
System.out.println("new Child Thread:" + t);
ThreadNum++;
t.start();
}
public void run(){
for(int i = 5; i > 0; i--){
System.out.println("ChildThread: " + i);
try{
Thread.sleep(500);
}catch(Exception e){
System.out.println("childThead Exception");
}
}
System.out.println("Exit ChildThread!");
}
}
public class NewThread{
public static void main(String[] args) throws Exception{
DemoThread nt = new DemoThread();
DemoThread nt2 = new DemoThread();
for(int i = 5; i > 0; i--){
System.out.println("MainThread:" + i);
Thread.currentThread().sleep(1000);
}
System.out.println("Exit MainThread!");
}
}
4。扩展(继承)Thread类新建线程,如:
public class TestThread extends Thread{
public TestThread(){
super("Demo Thread"); //注意这里
System.out.println("ChildThread Creadted:" + this);
start();
}
public void run(){
; //具体实现略
}
}
5。主线程一般必须最后结束。isAlive()函数判断一个线程是否已经结束。join()方法可用来等待它调用的线程终止。
6。线程优先级:get/setPriority方法。
7。同步方法:保证同一时刻只有一个线程访问方法,在方法定义前面加关键字:synchronized。
8。同步语句:将对外部类的方法的访问置于一个synchronized块中。synchronized(object){...;} 其中object是需要同步的对象的引用。
9。线程内通信:为了使用异步访问。wait()方法告诉调用这个函数的进程放弃监控器并进入睡眠状态,直到其他进程进入同一监控器并调用notify方法。notify方法唤醒第一个等待同一对象的线程。notify方法唤醒所有对同一个对象调用wait()的线程,最高优先级的先运行。
10。暂停、恢复、停止线程:不能使用suspend,resume和stop方法。应该用wait和notify方法。