多線程
来源:互联网 发布:搞笑的网络歌曲 编辑:程序博客网 时间:2024/05/17 02:14
如何創建線程
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.死鎖
- 多線程
- C#中的多線程 第三部分使用多線程
- C#中的多線程
- C#中的多線程
- 多線程同步(互斥)
- C#中的多線程1
- C#中的多線程
- 多線程之 CreateThread
- 多線程之WaitFor
- <python> 多線程/多進程/異步學習
- java多線程的實例
- 多線程之臨界區 (Critical Section)
- 多線程之TMultiReadExclusiveWriteSynchronizer(多讀一寫同步)
- C# 多線程的應用
- libxml++在多線程安全中的問題經驗總結
- C#中的多線程 第四部分 高級應用
- Android Native(JNI)層的多線程安全
- tcp + 阻塞 + 多線程 => 如何停止Recv()
- ANT十五大最佳实践
- 2005年湖北高考0分作文
- UDDI和WSDL的关系
- 关于标题
- 学编程的人不能不看的好文章
- 多線程
- DATAGRID的集中功能
- java.util.AbstractSet翻译
- Java WS和C#调用
- 最快速的两数交换
- 好文
- [MS Smartphone]Memory leak check
- 内容与标准为王:下一代互联网与下一代搜索
- Java开源项目Hibernate包作用详解