?? thread_2.java
字號:
package thread_static_1_2;
class TestThread {
public static Object lock=new Object(); //靜態(tài)鎖,鎖類,不是鎖對象了!!所以兩個(gè)線程同時(shí) 運(yùn)行兩個(gè) TestThread 的execute(),也可以同步!!!
public void execute(){ //
synchronized(lock){ for(int i=0;i<20;i++){//和execute1() 是等效的!!!
try {
Thread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+Thread.currentThread().getName()+" "+i);
}
}
}
public synchronized static void execute1(){ //如果這里不加 synchronized ,則不會(huì)同步,輸出還是交錯(cuò)的!!因?yàn)椋@個(gè)static 方法不用拿到鎖就可以運(yùn)行!!!
for(int i=0;i<20;i++){ //和execute() 是等效的!!!
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+Thread.currentThread().getName()+" "+i);
}
}
public static void execute2(){ //如果這里不加 synchronized ,則不會(huì)同步,輸出還是交錯(cuò)的!!因?yàn)椋@個(gè)static 方法不用拿到鎖就可以運(yùn)行!!!
synchronized(TestThread.class){
for(int i=0;i<20;i++){ //和execute() 是等效的!!!
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+Thread.currentThread().getName()+" "+i);
}
}
}
}
class ThreadA implements Runnable{
TestThread test=null;
public ThreadA(TestThread pTest){ //對象有外部引入,這樣 在需要的時(shí)候, 可以 保證是同一個(gè)對象,當(dāng)然也可以傳入不同的實(shí)例。比如下面main()。
test=pTest;
}
public void run() {
test.execute2();
}
}
public class Thread_2{
public static void main(String[] args){
TestThread test=new TestThread();//和下面的test2 生成不同的實(shí)例,也就要是 讓兩個(gè)線程 運(yùn)行的是兩個(gè)實(shí)例,再試驗(yàn)synchronized,
//
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
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -