读书人

线程实现开门后三秒自动关门

发布时间: 2013-07-04 11:45:33 作者: rapoo

线程实现开门后三秒自动关门 在线等
线程要实现 通过系统开锁 三秒后自动关锁
[解决办法]


private boolean flag=true;
public void setFlase(){
this.flag=false;
}
public void setTrue(){
this.flag=true;
}
public boolean getFlag(){
return flag;
}

public void run(){
while(true){
try {
Thread.currentThread().sleep(3000);//每个100毫秒刷新一次。标准为3000毫秒发射一个
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
this.setTrue();
//System.out.println("置为true");//等待超过三秒,把Flag置为true
}
}

[解决办法]

if(opendoor()==true){
try {
Thread.currentThread().sleep(3000);//线程休眠3000毫秒
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
closedoor();
}
opendoor和closedoor其实就是get和set方法。控制标记位flag这把锁
[解决办法]

class T extends Thread{
boolean flag=false;

public void run(){
while(true){
if(!flag){
flag=true;
try{
Thread.currentThread().sleep(3000);
}catch(Exception e){
e.printStackTrace();
}
System.out.println(flag);
}
flag=false;
}
}

[解决办法]
是不是这个意思


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TheLock implements Runnable{



private Condition openCondition;
private Condition closeCondition;
private Lock theLock;

public TheLock(){
theLock = new ReentrantLock();
openCondition = theLock.newCondition();
closeCondition = theLock.newCondition();
}

@Override
public void run() {
new Thread(new Open(theLock, openCondition)).start();
new Thread(new Close(theLock, closeCondition)).start();
while(true){
try {
if (openTheLock() == true){
theLock.lock();
openCondition.signalAll();
theLock.unlock();

Thread.sleep(3000);

theLock.lock();
closeCondition.signalAll();
theLock.unlock();
}else{
System.out.println("Open action failed");
}
Thread.sleep(100);


} catch (InterruptedException ex) {
ex.printStackTrace();
theLock.unlock();
}
}
}

private boolean openTheLock(){
return (System.nanoTime() % 3) == 1;
}

class Open implements Runnable{
private Lock lock;
private Condition openCondition;

Open(Lock lock, Condition openCondition){
this.lock = lock;
this.openCondition = openCondition;
}

@Override
public void run() {
while (true){
lock.lock();
try {
this.openCondition.await();
onOpen();
} catch (InterruptedException ex) {
ex.printStackTrace();
} finally {
lock.unlock();
}
}


}

protected void onOpen(){
System.out.println("Opened");
}

}


class Close implements Runnable{
private Lock lock;
private Condition closeCondition;

Close(Lock lock, Condition closeCondition){
this.lock = lock;
this.closeCondition = closeCondition;
}

@Override
public void run() {
while (true){
lock.lock();
try {
this.closeCondition.await();
onClose();
} catch (InterruptedException ex) {
ex.printStackTrace();
} finally {
lock.unlock();
}
}
}

protected void onClose(){
System.out.println("Closed");


}
}

public static void main(String[] args){
new Thread(new TheLock()).start();
}
}

读书人网 >J2SE开发

热点推荐