//执行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();
}
}