java多线程synchronized,wait,notify的大致用法
前段时间写了个多线程处理定时任务的问题,当时没有好好研究一下多线程的几个常用方法
这里我写了个小例子,望多指点
package com.sf.partner.mgt.thread;
/**
* wait();notify()必须在synchronized内部,而synchronized不一定需要wait()和notify()
* 同理有wait()就要有notify(),但有notify()不一定需要wait();,因为wait就是同步中需要异步
*/
public class ShThread implements Runnable{
public static void main(String args[]) {
// TODO Auto-generated method stub
ShThread sth1 = new ShThread();
Thread th1 = new Thread(sth1);
th1.start();
ShThread sth2 = new ShThread();
Thread th2 = new Thread(sth2);
th2.start();
ShThread sth3 = new ShThread();
Thread th3 = new Thread(sth3);
th3.start();
ShThread sth4 = new ShThread();
Thread th4 = new Thread(sth4);
th4.start();
}
private static long l = 0L;
private String s="";
@Override
public void run() {
synchronized(s) {//锁,同步代码块
l = 1+l;
System.out.println("l========"+l);
if(l==3) {
try {
s.wait();//wait我的理解就是同步中需要异步的时候使用来释放对象锁
//s.notify(); 注意这里不能放notify,放了就是个死循环
} catch (InterruptedException e) {
}
} else {
for(int i =0; i<10000; i++) {
Math.abs(i);
i = ++i;
for(int j =0; j<10000; j++) {
Math.abs(j);
j = ++j;
}
}
}
s.notify();//notify要放到执行wait()的条件外,唤醒其他某个线程竞争对象锁
}
}
}
转载于:https://blog.51cto.com/3131854/1264679