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)
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/374079/viewspace-132145/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/374079/viewspace-132145/
博客介绍了Java中线程的创建与同步方法。创建线程可通过实现Runnable接口或继承Thread类,且派生类必须重载run()方法。同步方面,当多线程共享资源时,需用同步机制确保资源某刻仅被一个线程占用,关键是管程(信号量)。
2425

被折叠的 条评论
为什么被折叠?



