java线程唤醒与等待_java学习笔记--线程等待与唤醒

//执行wait,notify(notifyAll)时必须获得对象锁,wait会释放锁

//sleep不会释放锁

import java.util.concurrent.locks.*;

import java.util.Scanner;

class Task implements Runnable

{

private Object lock = new Object();

public void run()

{

synchronized(lock)

{

System.out.println(Thread.currentThread().getName() + ":I' waiting for you");

try

{

lock.wait();

}

catch(InterruptedException e)

{

}

}

System.out.println(Thread.currentThread().getName() + ":I have wakeup");

}

public void wake()

{

synchronized(lock)

{

lock.notify();//lock.notifyAll();

}

}

}

class test

{

public static void main(String[] args)

{

Task task = new Task();

Thread thread = new Thread(task);

thread.start();

Scanner scanner = new Scanner(System.in);

System.out.println("input something to wake thread up");

String txt = scanner.nextLine();

//使用notify

//task.wake();

//使用interrupt

thread.interrupt();

}

}

//使用Lock

import java.util.concurrent.locks.*;

import java.util.Scanner;

class Task implements Runnable

{

private Lock lock = new ReentrantLock();

Condition condition = lock.newCondition();

Condition condition0 = lock.newCondition();//一个锁上创建可以创建多个条件变量

public void run()

{

try

{

lock.lock();

System.out.println(Thread.currentThread().getName() + ":I' waiting for you");

try

{

condition.await();

}

catch(InterruptedException e)

{

}

System.out.println(Thread.currentThread().getName() + ":I have wakeup");

}

finally

{

lock.unlock();

}

}

public void wake()

{

try

{

lock.lock();

condition.signal();//condition.signalAll();

}

finally

{

lock.unlock();

}

}

}

class test

{

public static void main(String[] args)

{

Task task = new Task();

Thread thread = new Thread(task);

thread.start();

Scanner scanner = new Scanner(System.in);

System.out.println("input something to wake thread up");

String txt = scanner.nextLine();

task.wake();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值