开心一笑
笑一笑十年少
受伤的乌龟
乌龟受伤。让蜗牛去买药。过了2个小时。蜗牛还没回来。乌龟急了骂道:他妈的再不回来老子就死了!这时门外传来了蜗牛的声音:你他妈再说老子不去了!
提出问题
解决问题
前面已经自我介绍了,今天是最后一次,我是超级奶爸,英文名:Object......这篇介绍完后,我就不再介绍我的,把机会留给我的子子孙孙们......
wait()
导致线程进入等待状态,直到它被其他线程通过notify()或者notifyAll唤醒。我有几个哥们:wait(long timeout) ,wait(long timeout, int nanos) ,timeout时间单位为毫秒,nano是毫微秒......
错误写法
/**
* Created by 阿毅 on 2016/2/26.
*/
public class TestObejct {
public synchronized void test() throws InterruptedException{
Thread thread = Thread.currentThread();//获得当前线程
System.out.println("Thread ID:" + thread.getId() + "Thread Name:" + thread.getName() );
}
}
/**
* Created by 阿毅 on 2016/2/26.
*/
public class ObjectWaitTest {
public static void main(String[] args) {
TestObejct testObejct = new TestObejct();
try {
testObejct.test();
testObejct.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- 执行结果回报错
- Object.wait()和Object.notify()和Object.notifyall()必须写在synchronized方法内部或者synchronized块内部
- synchronized就是针对内存区块申请内存锁(会在之后给出更多锁的介绍)
正确写法:
/**
* Created by 阿毅 on 2016/2/26.
*/
public class TestObejct {
public synchronized void test() throws InterruptedException{
Thread thread = Thread.currentThread();//获得当前线程
System.out.println("Thread ID:" + thread.getId() + "Thread Name:" + thread.getName() );
//wait();//一直傻傻的等,直到别人叫醒
wait(1000);//等1s
//wait(1000,100);//等一秒多啦
}
}
/**
* Created by 阿毅 on 2016/2/26.
*/
public class ObjectWaitTest {
public static void main(String[] args) {
TestObejct testObejct = new TestObejct();
try {
testObejct.test();
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread thread = Thread.currentThread();
System.out.println("Thread ID:" + thread.getId()
+ "Thread Name" + thread.getName());
}
}
//结果 打印两次相隔1s
Thread ID:1Thread Name:main
Thread ID:1Thread Namemain
notify()
唤醒在此对象监视器上等待的单个线程
> 以下代码引用:http://www.cnblogs.com/dolphin0520/p/3920385.html
/**
* Created by 阿毅 on 2016/2/26.
*/
public class ObjectNotifyTest {
public static Object object = new Object();
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
thread1.start();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread2.start();
}
static class Thread1 extends Thread{
@Override
public void run() {
synchronized (object) {
try {
object.wait();
} catch (InterruptedException e) {
}
System.out.println("线程"+Thread.currentThread().getName()+"获取到了锁");
}
}
}
static class Thread2 extends Thread{
@Override
public void run() {
synchronized (object) {
object.notify();
System.out.println("线程"+Thread.currentThread().getName()+"调用了object.notify()");
}
System.out.println("线程"+Thread.currentThread().getName()+"释放了锁");
}
}
}
//运行结果
线程Thread-1调用了object.notify()
线程Thread-1释放了锁
线程Thread-0获取到了锁
- 上面代码都是对object进行加锁的。
- 从上面运行结果可以知道,一个线程被唤醒不代表立即获取了对象的monitor,
只有等调用完notify()或者notifyAll()并退出synchronized块,释放对象锁后,其余线程才可获得锁执行。
notifyAll()
唤醒所有在此对象监视器上等待的单个线程
优秀文章
读书感悟
来自《泰坦尼克号》
- you jump ,I jump......
- 要让每一天有所值
- 别这样,坚持下去,你明白吗?