開辟線程的兩種方式
阿新 • • 發佈:2018-01-28
sta reads 獨立 mailto implement thread 執行 threads 避免 /**
- 自定義執行單元的兩種方式
- 區別
- runnable避免了單繼承的局限性
- runnable資源可以被獨立共享
- 多線程如何找問題
1.明確哪些代碼是多線程運行代碼
2.明確哪些是共享數據
3.明確多線程代碼中哪些語句是操作共享數據的 - @author WangShuang
-
/
public class Test {
public static void main(String[] args) {
/MyThread t0=new MyThread();
MyThread t1=new MyThread();
t0.start();
t1.start();//出現兩百張票
*/
//t0.start();//java.lang.IllegalThreadStateException/*MyRunnable r=new MyRunnable(); Thread rt0 = new Thread(r); Thread rt1 = new Thread(r); rt0.start(); rt1.start();*/
}
}
/** - 方式1繼承Thread
- 如果想實現兩個窗口買票的話
- MyThread t0=new MyThread();
MyThread t1=new MyThread();
t0.start();
t1.start();//出現兩百張票
如果在tick前面加static能解決問題,但是生命周期又太長,所以采用方式2 - @author Administrator
-
/
class MyThread extends Thread{
br/>@Override
while(tick>0){
System.out.println(tick--);
}
}
}
/** - 方式2實現Runnable接口
- @author Administrator
-
*/
class MyRunnable implements Runnable {
int tick = 100;@Override
br/>@Override
synchronized (new Object()) {
while(tick>0){
System.out.println(" "+this.toString());
}
}
}
}
開辟線程的兩種方式