两个线程增加操作,两个线程减操作
package test;
public class MyThread {
/**
* @param args
*/
static MyThread mt=new MyThread();
static int data =100;
public static void main(String[] args) throws Exception {
Thread t1=new Thread(new dec());
t1.setName("第一减线程");
Thread t2=new Thread(new dec());
t2.setName("第二减线程");
Thread t3=new Thread(new inc());
t3.setName("第一增线程");
Thread t4=new Thread(new inc());
t4.setName("第二增线程");
t1.start();
t2.start();
t3.start();
t4.start();
}
static class dec implements Runnable{
@Override
public void run() {
while(true){
synchronized(mt){
//mt.notify();
data--;
System.out.println(Thread.currentThread()+" data: "+ data);
try {
//mt.wait();
Thread.sleep(1000*1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
static class inc implements Runnable{
@Override
public void run() {
while(true){
synchronized(mt){
//mt.notify();
data++;
System.out.println(Thread.currentThread()+" data: "+ data);
try {
//mt.wait();
Thread.sleep(1000*1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
去掉 通知和等待的结果
添加通知和等待的结果
可见有了通知和等待,线程执行一次后 会主动释放资源,而不是 只是等待 操作系统进行调度 ,完全靠抢占式的调度方式,往往达不到我们想要的结果
关于synchronized 的用法还可以参考:
http://blog.csdn.net/weizhaozhe/article/details/3922647