Java 我没有使用synchronized关键字,而是使用了锁的概念,但我没有像在synchronized关键字中那样获得输出?
MoveJava 我没有使用synchronized关键字,而是使用了锁的概念,但我没有像在synchronized关键字中那样获得输出?,java,Java,MoveReentrantLock lock=new ReentrantLock()在您的方法之外 import java.util.concurrent.locks.ReentrantLock; class Displayx { public void wish(String name) { ReentrantLock lock = new ReentrantLock(); //using locks lock.lock
ReentrantLock lock=new ReentrantLock()代码>在您的方法之外
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();
}
}
ReentrantLock lock=new ReentrantLock();
公共无效信息(字符串名称)
{
//使用锁
lock.lock();
试一试{
对于(int i=0;i<10;i++){
System.out.print(“早上好:”);
试一试{
《睡眠》(2000年);
}捕捉(中断异常e){
System.out.println(“我得到了intruppted”);
}
System.out.println(名称);
}
}最后{
lock.unlock();
}
}
在Java中,在方法中创建的变量可以在同一线程中访问(作用域)
当您的ReentrantLock
对象在wish
()方法中创建时,它是每个线程的本地对象。也就是说,您实际上是在为每个线程创建单独的lock
对象,因为多个线程正在进入您的关键部分代码(在try
块中)
classdisplayx
{
ReentrantLock lock=new ReentrantLock();//使用相同的锁对象
公共无效信息(字符串名称)
{
//使用锁
lock.lock();
试一试{
对于(int i=0;i<10;i++){
System.out.print(“早上好:”);
试一试{
《睡眠》(2000年);
}捕捉(中断异常e){
System.out.println(“我得到了intruppted”);
}
System.out.println(名称);
}
}最后{
lock.unlock();
}
}
}
此外,正如Boris在评论中提到的,确保您是通过使用Runnable
或Callable
接口而不是直接扩展Thread
类来“编码到接口”的。使用相同的Lock
?就像您需要在同一个对象上同步。事实上,在这种情况下,使用Lock
并没有任何好处——当锁需要交错时,它会自动产生……也许更重要的是,不要扩展线程。(除非你知道自己在做什么并且有充分的理由)@Boristespider为什么不扩展线程
?请链接到解释原因的文章@Andreas.@Andreas它可能相当危险-例如,在线程上使用等待
和通知
可能会产生意想不到的后果,因为线程
在内部通知自己死亡。出于各种原因,通常最好避免。
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();
}
}
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();
}
}
}