import java.util.concurrent.locks.ReentrantLock;
class Displayx
{
public void wish(String name)
{
ReentrantLock lock = new ReentrantLock();
//using locks
lock.lock();
for (int i = 0; i < 10; i++)
{
System.out.print("Good Morning : ");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("I got intruppted");
}
System.out.println(name);
}
lock.unlock();
}
}
class MyThreadex2 extends Thread
{
Displayx d;
String name;
public MyThreadex2(Displayx d, String name)
{
this.d = d;
this.name = name;
}
@Override
public void run()
{
d.wish(name);
}
}
public class ReentrantLockDemo1 {
public static void main(String[] args)
{
Displayx d = new Displayx();
MyThreadex2 mt1 = new MyThreadex2(d, "SHOAIB");
MyThreadex2 mt2 = new MyThreadex2(d, "RAHUL");
mt1.start();
mt2.start();
}
}
輸出我得到是而不是使用同步關鍵字我正在使用鎖定概念,但我沒有得到輸出,因爲我在同步關鍵詞中獲得?
Good Morning : Good Morning : SHOAIB
Good Morning : RAHUL
Good Morning : RAHUL
Good Morning : SHOAIB
Good Morning : SHOAIB
Good Morning : RAHUL
Good Morning : RAHUL
Good Morning : SHOAIB
Good Morning : SHOAIB
Good Morning : RAHUL
Good Morning : SHOAIB
Good Morning : RAHUL
Good Morning : SHOAIB
Good Morning : RAHUL
Good Morning : RAHUL
Good Morning : SHOAIB
Good Morning : SHOAIB
Good Morning : RAHUL
Good Morning : RAHUL
SHOAIB
使用**相同**'Lock'?就像你需要在同一個對象上「同步」一樣。事實上,在這種情況下,使用'Lock'沒有任何好處 - 當鎖需要交錯時,它會自動進入... –
也許更重要的是,**不要'擴展Thread' **。 (除非你知道你在做什麼,並有很好的理由) –
@BoristheSpider爲什麼不'擴展線程?請鏈接到解釋原因的文章。 – Andreas