线程lock condition使用

is668com 2012-10-26 09:43:57
下面是具体例子,一直抛错,搞不懂应该怎么用了;求修改求思想
package com.sixth.exam;

import java.util.concurrent.locks.*;

public class T3{
public static void main(String[] args)
{

ReentrantLock lock=new ReentrantLock();
PrintThread pt=new PrintThread(lock);
Thread t=new Thread(pt);
t.start();
}
}
class PrintThread implements Runnable
{

ReentrantLock lock;
Condition condition;
PrintThread1 pt1;
Thread t1;
public PrintThread(ReentrantLock lock)
{
this.lock=lock;
condition=lock.newCondition();
pt1=new PrintThread1(lock);
t1=new Thread(pt1);
}
public void run()
{
t1.start();
for(int i=3;i>=0;i--)
{
System.out.println(i+"....");
if(i==1)
{
System.out.println("起床啦");
condition.signalAll();
}
}

}
}
class PrintThread1 implements Runnable
{
ReentrantLock lock;
Condition condition;
public PrintThread1(ReentrantLock lock)
{
this.lock=lock;
condition=lock.newCondition();
}
public void run()
{
try {
lock.newCondition().await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("复活了~");
}
}
...全文
106 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
is668com 2012-10-26
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

Java code

import java.util.concurrent.locks.*;

public class T3 {
public static void main(String[] args) {

ReentrantLock lock = new ReentrantLock();
PrintThread pt = new PrintT……
[/Quote]
怎么设置加锁的位置?
我在不同的代码块加锁Console输出的不同
Kanepan 2012-10-26
  • 打赏
  • 举报
回复
你就把lock.lock()当做synchronized(object);
但是记得必须要 lock.unlock();
不是十分有把握的情况下,尽量用synchronized,简单,易懂。性能上的差距只是代码级的。
Kanepan 2012-10-26
  • 打赏
  • 举报
回复

import java.util.concurrent.locks.*;

public class T3 {
public static void main(String[] args) {

ReentrantLock lock = new ReentrantLock();
PrintThread pt = new PrintThread(lock);
Thread t = new Thread(pt);
t.start();
}
}

class PrintThread implements Runnable {

ReentrantLock lock;
Condition condition;
PrintThread1 pt1;
Thread t1;

public PrintThread(ReentrantLock lock) {
this.lock = lock;
condition = lock.newCondition();
pt1 = new PrintThread1(lock, condition);
t1 = new Thread(pt1);
}

public void run() {
t1.start();
for (int i = 3; i >= 0; i--) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(i + "....");
if (i == 1) {
System.out.println("起床啦");
lock.lock();
try {
condition.signal();
} finally {
lock.unlock();
}
}
}

}
}

class PrintThread1 implements Runnable {
ReentrantLock lock;
Condition condition;

public PrintThread1(ReentrantLock lock, Condition condition) {
this.lock = lock;
this.condition = condition;
}

public void run() {
lock.lock();
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
System.out.println("复活了~");
}
}

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧