如何创建线程
Thread 类定义了多种方法可以被派生类重载,,必须重载run()方法
1.实现Runnable接口
如果你不需要重载Tread的其它方法时,最好只实现Runnable接口
// Create Thread method one is implements Runnable
class NewThread implements Runnable{
Thread t;
NewThread(){
t = new Thread(this,"DemoThread");
System.out.println("child thread : "+t);
t.start();
}
public void run(){
try{
for (int n =5; n>0 ; n--){
System.out.println("Child thread "+n);
Thread.sleep(500); // Child 500
}
}catch(InterruptedException e){
System.out.println("Child thread interrupted ");
}
System.out.println("Child thread exiting ");
}
}
2 .可以继承Thread类
如果类仅在他们被加强或修改时应该被扩展
// Create Thread the other method is extends Thread
class NewThread2 extends Thread{
NewThread2(){
super("Demo Thread");
System.out.println("child thread : "+this);
start();
}
public void run(){
try{
for (int n =5; n>0 ; n--){
System.out.println("Child thread "+n);
Thread.sleep(500); // Child 500
}
}catch(InterruptedException e){
System.out.println("Child thread interrupted ");
}
System.out.println("Child thread exiting ");
}
}
同步
1. 当两个或两个线程需要共享资源,他们需要某种方法来确定资源在某一刻仅被一个线程占用,叫同步(synchronization)
2. 同步关键时管程(也叫信号量semaphone).管程是一个互斥占锁定的对象,或称互斥体(mutex)====================================
1.创建线称的两个方法
2.t.join() 用于 控制主线程知道子线程何时结束 ,少用t.isAlive()
3.Priority
Level的值必须在MIN_PRIORITY到MAX_PRIORITY范围内。通常,它们的值分别是1和10。要返回一个线程为默认的优先顺序,指定NORM_PRIORITY,通常值为5。这些优先顺序在Thread中都被定义为final型变数。(volatile的运用阻止了该优化)
4. synchronization
to method
class Callme {
synchronized void call(String msg) {
...
}
调用第3方类时
ThirdClass tc = new ThirdClass()
synchronized(tc) {
// statements to be synchronized
}
5.wait( ),notify( )和notifyAll( ) 这三个方法仅在synchronized方法中才能被调用
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
6.死锁