java multithreading data sharing, thread synchronization and mutual exclusion

EDITORIAL

This article is incorporated by ticketing system, for example, Jane v two ways to share data among multiple threads of java, thread synchronization. Article may have many shortcomings, please understand, welcome Gangster comments.

As used herein, the thing

  1. java
  2. eclipse 2019-11

1. multi-threaded shared data

1.1 Share Runnable

  When the same content a plurality of threads of execution may be employed Runnable interface class object sharing manner shared data, the shared data object as a member variable Runnable.
  Here we ticketing system including a plurality of ticket office, for example, a ticket for each thread, multiple threads share more than the number of votes variables.

class TicketRunnable implements Runnable{
	private int num;
	
	public TicketRunnable(int num) {
		this.num=num;
	}
	@Override
	public void run() {
		for(int i=0;i<5;i++) {	//出售5张票
			if(num>0) {
				num--;
				System.out.println(Thread.currentThread().getName()+":售票1张,余票"+num);
			}else {
				System.out.println(Thread.currentThread().getName()+":暂时无余票");
			}
		}
	}
}
public class 多线程共享数据 {
	public static void main(String[] args) {
		Runnable runnable = new TicketRunnable(8);	//初始化8张余票
		new Thread(runnable,"武汉售票点").start();
		new Thread(runnable,"北京售票点").start();
	}
}

1.2 encapsulation data objects

  When a method is executing a plurality of threads shared Runnable object may be employed to share the same variables operation, this method is not suitable for performing different operations may be packaged into shared data objects, the object is shared by multiple threads.
  To the ticketing system, for example, a thread of execution refund, a thread of execution ticket.

class Ticket{
	private int num;
	public Ticket(int num) {
		this.num=num;
	}
	public void sell() {
		if(num>0) {
			num--;
			System.out.println(Thread.currentThread().getName()+":售票1张,余票"+num);
		}else {
			System.out.println(Thread.currentThread().getName()+":暂时无余票");
		}
	}
	public void returned() {
		num++;
		System.out.println(Thread.currentThread().getName()+":退票1张,余票"+num);
	}
}
public class 多线程共享数据 {
	public static void main(String[] args) {
		Ticket ticket = new Ticket(8);	//初始化为8张票
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0;i<8;i++) {
					ticket.sell();//售票
				}
			}
		},"售票处").start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0;i<8;i++) {
					ticket.returned();//退票
				}
			}
		},"退票处").start();
	}
}

2. Thread Synchronization and mutual exclusion

Code above problems 2.1

Runnable shared object implementation in a synchronized manner, for example, run the program, the results are as follows:

武汉售票点:售票1张,余票6
武汉售票点:售票1张,余票5
北京售票点:售票1张,余票6
武汉售票点:售票1张,余票4
武汉售票点:售票1张,余票2
北京售票点:售票1张,余票3
北京售票点:售票1张,余票0
北京售票点:暂时无余票
北京售票点:暂时无余票
武汉售票点:售票1张,余票1

  The initial number of votes we set for 8 to view operating results, not many tickets available from 7 to start decreasing, but from June, and is not diminishing. The issue occurs because the ticket Wuhan votes minus time point 1 has not been output, the Beijing ticket will also reduce the number of votes to 1, which is 6 times the output. Not by decreasing output also because the read data has not been output, another thread executes the ticket output. TicketRunnable of the run()method slightly modified, amended as

	@Override
	public void run() {
		for(int i=0;i<5;i++) {	//出售5张票
			synchronized (this) {
				if(num>0) {
					num--;
					System.out.println(Thread.currentThread().getName()+":售票1张,余票"+num);
				}else {
					System.out.println(Thread.currentThread().getName()+":暂时无余票");
				}
			}
		}
	}

In this case, the output is the program contents in descending order, synchronized to the code block as a synchronization lock, and modifying the value of the value of the synchronization operations, it will not scrambled, the output I is incorrect ticket appears.

2.2 synchronization and mutual exclusion

1. What are mutually exclusive?
In many computer resources are limited, this limited resource is called critical resources. Multiple processes compete for the same critical resource, you can grab a run, did not grab will not run. Competition for indirect relationship is mutually exclusive critical resource constraints of the process. For example, multiple threads compete for a printer to print resources, inter-process mutex is formed.

2. What is synchronization?
Synchronization is the coordination of multiple interrelated threads cooperation to complete the task, there are some constraints between each other, the order of execution is often ordered. Synchronization is directly restricts the relationship between processes, such as supply and marketing system, needs to be stopped when the warehouse is full supply, warehouse shipments not empty, then the process of delivery and sales process to form a synchronous relationship.

2.3 synchronized to achieve synchronization

The method can be used to modify synchronized, static methods and code blocks

//对象锁,修饰方法
synchronized void a() {

}
//类锁,修饰静态方法
synchronized static void b() {

}
void c() {
	//对象锁,修饰代码块
	synchronized (this) {
			
	}
	//类锁,修饰代码块
	synchronized (Ticket.class) {

	}	
}

2.4 ReentrantLock synchronization

1. Use

ReentrantLock lock = new ReentrantLock();
lock.lock();	//加锁
lock.unlock();	//解锁

2. To achieve the above-described synchronization ticketing

class TicketRunnable implements Runnable{
	private int num;
	ReentrantLock lock = new ReentrantLock();
	
	public TicketRunnable(int num) {
		this.num=num;
	}
	@Override
	public void run() {
		for(int i=0;i<5;i++) {	//出售5张票
			lock.lock();
			if(num>0) {
				num--;
				System.out.println(Thread.currentThread().getName()+":售票1张,余票"+num);
			}else {
				System.out.println(Thread.currentThread().getName()+":暂时无余票");
			}
			lock.unlock();
		}
	}
}
public class 多线程共享数据 {
	public static void main(String[] args) {
		Runnable runnable = new TicketRunnable(8);	//初始化8张余票
		new Thread(runnable,"武汉售票点").start();
		new Thread(runnable,"北京售票点").start();
	}
}

3. Summary

synchronized implementation is synchronous or mutually exclusive somewhat difficult to understand this point, the Internet also has said that the mutex is synchronized, synchronized implementation is a modified content synchronization. There are ambiguities Comments welcome, I would see the reply. This article is over, what are deficiencies please feel free to correct me.

Published 42 original articles · won praise 22 · views 7985

Guess you like

Origin blog.csdn.net/nineya_com/article/details/104059103
Recommended