多线程对同一数据进行不同操作

示例一:网上多数采用的方法,设计得很巧妙

import java.util.concurrent.atomic.AtomicInteger;

public class AddSub {
	
	AtomicInteger at = new AtomicInteger(1);
	int j = 1;

	public static void main(String[] args) {
		AddSub ab = new AddSub();
		Add a = ab.new Add();
		Sub b = ab.new Sub();
		Thread t1 = new Thread(a);
		Thread t2 = new Thread(a);
		Thread t3 = new Thread(b);
		Thread t4 = new Thread(b);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
	
	public synchronized void add(){
		j++;
		System.out.println("add:"+j);
	}
	
	public synchronized void sub(){
		j--;
		System.out.println("sub:"+j);
	}

	class Add implements Runnable{
		@Override
		public void run() {
			for(int i=0;i<20;i++){
				add();
			}
			
		}
	}
	
	class Sub implements Runnable{
		@Override
		public void run() {
			for(int i=0;i<20;i++){
				sub();
			}
			
		}
	}
}
示例二:采用将数据封装到一个类中进行处理

public class AddSub1 {
	
	int j = 10;

	public static void main(String[] args) {
		final Sub s = new Sub();
		for(int i=0;i<2;i++){
			new Thread(new Runnable() {
				@Override
				public void run() {
					s.add();
				}
			}).start();
			new Thread(new Runnable() {
				@Override
				public void run() {
					s.sub();
				}
			}).start();
		}

	}
	
}

class Sub{
	int j = 10;
	public synchronized void add(){
		j++;
		System.out.println("add:"+j);
	}
	
	public synchronized void sub(){
		j--;
		System.out.println("sub:"+j);
	}
}



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