?? thread_2.java
字號(hào):
package thread_static_1;
class TestThread {
public static Object lock=new Object(); //靜態(tài)鎖,鎖類,不是鎖對(duì)象了!!所以兩個(gè)線程同時(shí) 運(yùn)行兩個(gè) TestThread 的execute(),也可以同步!!!
public void execute(){ //
synchronized(lock){ for(int i=0;i<20;i++){
try {
Thread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+Thread.currentThread().getName()+" "+i);
}
}
}
}
class ThreadA implements Runnable{
TestThread test=null;
public ThreadA(TestThread pTest){ //對(duì)象有外部引入,這樣 在需要的時(shí)候, 可以 保證是同一個(gè)對(duì)象,當(dāng)然也可以傳入不同的實(shí)例。比如下面main()。
test=pTest;
}
public void run() {
test.execute();
}
}
public class Thread_2{
public static void main(String[] args){
TestThread test=new TestThread();//和下面的test2 生成不同的實(shí)例,也就要是 讓兩個(gè)線程 運(yùn)行的是兩個(gè)實(shí)例,再試驗(yàn)synchronized,
//證明了 public synchronized void execute() 鎖定的是一個(gè)實(shí)例,而不是 整個(gè)類。
Runnable runabble=new ThreadA(test);
TestThread test2=new TestThread();//
Runnable runabble2=new ThreadA(test2);
Thread a=new Thread(runabble,"A");
a.start();
Thread b=new Thread(runabble2,"B");
b.start();
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -