多线程间共享对象和数据方式

(一)若每个线程执行的代码相同,可以用同一个Runnable对象,Runnable里面有共享的对象和数据,例如卖票系统,5个线程共同卖100张票

public class ThreadTest2 {
	
	public static void main(String[] args) {
		ShareTicket  shareTicket=new ShareTicket();
		new  Thread(shareTicket).start();
		new  Thread(shareTicket).start();
		new  Thread(shareTicket).start();
		new  Thread(shareTicket).start();
		new  Thread(shareTicket).start();
	}
}

class ShareTicket implements Runnable{
	private int ticket=100;
	@Override
	public void run() {
		for(int i=1;i<=100;i++){
			if(ticket>0){
				System.out.println("当前线程:"+Thread.currentThread().getName()+"剩余的票:"+ticket--);
			}
		}
	}
}

(二)若每个线程执行的代码不同,则需要不同的Runnable对象来实现Runnable间的数据共享,例如:设计4个线程,其中2个线程每次对j加1,2个线程每次对j减1

public class ThreadTest2 {

	private int j;

	public static void main(String[] args) {

		ThreadTest2 many = new ThreadTest2();
		Inc inc = many.new Inc();
		Dec dec = many.new Dec();
		for (int i = 0; i < 2; i++) {
			Thread t = new Thread(inc);
			t.start();
			t = new Thread(dec);
			t.start();
		}
	}

	private synchronized void inc() {
		j++;
		System.out.println(Thread.currentThread().getName() + "inc" + j);
	}

	private synchronized void dec() {
		j--;
		System.out.println(Thread.currentThread().getName() + "dec" + j);
	}

	class Inc implements Runnable {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			for (int i = 0; i < 20; i++) {
				inc();
			}
		}

	}

	class Dec implements Runnable {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			for (int i = 0; i < 20; i++) {
				dec();
			}
		}

	}
}


你可能感兴趣的:(多线程与并发库高级应用,Java,Java编程之路)