线程访问共享数据的3种方法

方法一:用内部类作为线程,根据内部类可以访问外部类的全部成员的特性将拥有共享数据的类定义为外部类的成员变量或方法中的局部变量,代码如下

public class MultiThread {
	private static ShareData data = new ShareData();

	public static void main(String[] args) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				data.decrement();
			}
		}).start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				data.increment();
			}
		}).start();
	}

}

class ShareData {
	private int j = 0;

	public synchronized void increment() {
		for (int i = 0; i < 100; i++) {
			j++;
			System.out.println(Thread.currentThread().getName() + ":" + j);
		}
	}

	public synchronized void decrement() {
		for (int i = 0; i < 100; i++) {
			j++;
			System.out.println(Thread.currentThread().getName() + ":" + j);
		}
	}
}


方法二:将共享数据封装到一个对象,将这个对象传递给多个Runnable对象,每个线程对共享数据的操作方法也分配到那个对象身上完成,这样容易实现针对该数据进行的各个操作的互斥和通信,代码如下

public class MultiThread {
	public static void main(String[] args) {
		final ShareData data = new ShareData();
		new Thread(new MyRunnable1(data)).start();
		new Thread(new MyRunnable2(data)).start();
	}

}

class MyRunnable1 implements Runnable {
	private ShareData data;

	public MyRunnable1(ShareData data) {
		this.data = data;
	}

	@Override
	public void run() {
		data.decrement();
	}
}

class MyRunnable2 implements Runnable {
	private Sharedata data;

	public MyRunnable2(Sharedata data) {
		this.data = data;
	}

	@Override
	public void run() {
		data.increment();
	}
}

class Sharedata {
	private int j = 0;

	public synchronized void increment() {
		for (int i = 0; i < 100; i++) {
			j++;
			System.out.println(Thread.currentThread().getName() + ":" + j);
		}
	}

	public synchronized void decrement() {
		for (int i = 0; i < 100; i++) {
			j--;
			System.out.println(Thread.currentThread().getName() + ":" + j);
		}
	}
}


方法三:将共享数据定义为主类的成员变量,将需要同步的方法定义为主类的成员方法,代码如下

public class MultiThread {
	private int j;

	public static void main(String[] args) {
		MultiThread mt = new MultiThread();
		Dec dec = mt.new Dec();
		Inc inc = mt.new Inc();
		new Thread(inc).start();
		new Thread(dec).start();
	}

	class Dec implements Runnable {
		@Override
		public void run() {
			for (int i = 0; i < 100; i++) {
				decrement();

			}
		}
	}

	class Inc implements Runnable {
		@Override
		public void run() {
			for (int i = 0; i < 100; i++) {
				increment();
			}
		}
	}

	public synchronized void increment() {
		j++;
		System.out.println(Thread.currentThread().getName() + ":" + j);
	}

	public synchronized void decrement() {
		j--;
		System.out.println(Thread.currentThread().getName() + ":" + j);
	}

}


你可能感兴趣的:(多线程)