方法名称 | 描述 |
notify() | 随机选择一个在该对象上调用wait()方法的线程,从等待队列转移到同步队列 |
notifyAll() | 解除所有在该对象上调用wait()方法的线程,所有线转移到等待队列 |
wait() | 调用该方法使线程进入waiting状态,只有等待其他线程通知和中断才会返回,调用wait()方法回释放锁 |
wait(long) | 等待一段时间,如果没有通知就超时返回 |
wait(long,int) | 对超时时间更细粒度的控制,可以达到纳秒 |
public class WaitNotify {public class Piped {
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
PipedWriter out = new PipedWriter();
PipedReader in = new PipedReader();
//将输出流和输入流进行链接
out.connect(in);
Thread thread = new Thread(new Print(in),"printThread");
thread.start();
int receive=0;
try {
while ((receive=System.in.read())!=1) {
out.write(receive);
}
} finally{
out.close();
}
}
static class Print implements Runnable{
private PipedReader in;
public Print(PipedReader in) {
super();
this.in = in;
}
@Override
public void run() {
int receive =0;
try {
while((receive=in.read()) !=1){
System.out.println((char)receive);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}public class Join {
public static void main(String[] args) throws InterruptedException {
Thread currentThread = Thread.currentThread();
for (int i = 0; i <10; i++) {
Thread thread = new Thread(new Domino(currentThread),i+"");
thread.start();
currentThread=thread;
}
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName());
}
static class Domino implements Runnable{
private Thread thread;
public Domino(Thread thread) {
super();
this.thread = thread;
}
public void run() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
}public class ThreadLocalTest {
private static final ThreadLocal<Long> TIME_THREADLOCAL = new ThreadLocal<Long>();
public static void main(String[] args) throws InterruptedException {
ThreadLocalTest.begin();
System.out.println(ThreadLocalTest.end());
}
/**
* 将一个值存放到本地线程中
*/
public static final void begin(){
TIME_THREADLOCAL.set(System.currentTimeMillis());
}
/**
* 将一个中从本地线程中取出
* @return
* @throws InterruptedException
*/
public static final long end() throws InterruptedException{
Long begin = TIME_THREADLOCAL.get();
TimeUnit.SECONDS.sleep(1);
return begin-System.currentTimeMillis();
}
}| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |