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
答案 0 :(得分:0)
将ReentrantLock lock = new ReentrantLock();
移出您的方法之外。
ReentrantLock lock = new ReentrantLock();
public void wish(String name)
{
//using locks
lock.lock();
try {
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);
}
} finally {
lock.unlock();
}
}
答案 1 :(得分:0)
在Java中,在方法内创建的变量可以在同一个线程中访问(作用域)。
在ReentrantLock
()方法中创建wish
对象时,它对每个线程都是本地的。即您实际上是在创建个人lock
每个线程的对象,因为多个线程正在进入您的关键部分代码(在try
块内)。
class Displayx
{
ReentrantLock lock = new ReentrantLock();//Use the same lock object
public void wish(String name)
{
//using locks
lock.lock();
try {
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);
}
} finally {
lock.unlock();
}
}
}
另外,正如Boris在评论中提到的那样,请确保使用Runnable
或Callable
接口而不是直接扩展Thread
类来“编码接口”。