synchronized 中 notify 與wait() 的用法

兩個線程增加操作,兩個線程減操作

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章