多线程共享数据案例

 
/**
 * 多线程共享数据(设计四个线程,其中两个线程对J加1,两个线程对J减1)
 * @author tanfei
 * @date 2012-02-03
 */
public class MultiThreadShareData {
	
	private static MyShareData shareData = new MyShareData();
	
	public static void main(String[] args) {
		final MyShareData myShareData = new MyShareData();
		/*设计四个线程*/
		//线程一
		new Thread(new MyRunnable1(shareData)).start();
		//线程二
		new Thread(new MyRunnable2(shareData)).start();
		
		//线程三 (增加操作)
		new Thread(new Runnable(){
			@Override
			public void run() {
				while(true)
				{
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					myShareData.increment();
				}
			}
		}).start();
		//线程四(减少操作)
		new Thread(new Runnable(){

			@Override
			public void run() {
				while(true)
				{
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					myShareData.decrement();
				}
			}
			
		}).start();
	}

}

class MyRunnable1 implements Runnable{

	@Override
	public void run() {
		while(true)
		{
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			shareData.increment();
		}
	}
	
	private MyShareData shareData = new MyShareData();
	
	public MyRunnable1(MyShareData shareData)
	{
		this.shareData = shareData;
	}
}

class MyRunnable2 implements Runnable{

	@Override
	public void run() {
		while(true)
		{
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			shareData.decrement();
		}
	}
	
	private MyShareData shareData = new MyShareData();
	
	public MyRunnable2(MyShareData shareData)
	{
		this.shareData = shareData;
	}
}

class MyShareData{
	private int j = 0;
	
	public synchronized void increment()//增加操作
	{
		j++;
		System.out.println(Thread.currentThread().getName() + "increment 当前j的值为:" + j);
	}
	
	public synchronized void decrement()//减少操作
	{
		j--;
		System.out.println(Thread.currentThread().getName() + "decrement 当前j的值为:" + j);
	}
}
相关文章
相关标签/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
公众号推荐
   一个历史类的公众号,欢迎关注
一两拨千金