How Java- resolve conflicts among multiple threads to shared resources

Shared among multiple threads to solve the problem of resource conflicts

1. Conflict show:

/*
 * 共享资源冲突的问题
 */
class SingleThread implements Runnable {

	// 共享资源,100张票
	private static int ticket = 100;

	@Override
	public void run() {
		while (true) {
			if (ticket > 0) {
				System.out.println(Thread.currentThread().getName() +
				 "售出了第" + ticket + "张票");
				ticket -= 1;
				
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				System.out.println(Thread.currentThread().getName() +
				 "售罄!!!");
				break;
			}
		}
	}
}

public class Demo1 {
	public static void main(String[] args) {
		Thread thread = new Thread(new SingleThread(),"淘票票");
		Thread thread2 = new Thread(new SingleThread(),"猫眼");
		Thread thread3 = new Thread(new SingleThread(),"美团");
		
		thread.start();
		thread2.start();
		thread3.start();
	}
}

Here Insert Picture Description
Here Insert Picture Description
You can see from the above example, every last ticket is sold once a platform, like this is certainly not in line with the actual situation, which is that we need to solve this problem.

2. Solution:

2.1 synchronized block
  1. format:
synchronized ("锁") {
	//需要同步的代码
}
  1. Wherein:
    A: the synchronized parentheses after the keyword inside the object is a lock object , and if required in the case of multi-thread, lock object must be unique .
    b: the code synchronized braces that need to be synchronized code, or lock code, the contents inside the braces and the time that allows only one thread class object into the operation performed, the remaining thread needs to wait for this thread class object unlock to enter the class object.
    c: sync block code as short as possible , to ensure the safety at sufficiently improve performance.
// 1. 使用同步代码块解决多线程中共享资源冲突的问题
 
/**
 * 自定义售票线程类
 * 
 * @author 
 *
 */
//同步代码块
class SingleThread1 implements Runnable {

	// 共享资源,100张票
	private static int ticket = 100;

	@Override
	public void run() {
		while (true) {
			synchronized ("锁") {

				if (ticket > 0) {
					System.out.println(Thread.currentThread().getName() +
					 "售出了第" + ticket + "张票");
					ticket -= 1;

					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					System.out.println(Thread.currentThread().getName() +
					 "售罄!!!");
					break;
				}
			}
		}
	}
}

public class Demo2 {
	public static void main(String[] args) {
		Thread thread = new Thread(new SingleThread1(), "淘票票");
		Thread thread2 = new Thread(new SingleThread1(), "猫眼");
		Thread thread3 = new Thread(new SingleThread1(), "美团");

		thread.start();
		thread2.start();
		thread3.start();
	}
}
2.2 synchronous method
  • What is synchronization method: Use the synchronized keyword method is modified synchronization method, there is a synchronization method and only allows one thread into the class object to perform operations.
2.2.1 static synchronized method
  • Static method is modified using the synchronized keyword static synchronized methods, static lock object synchronization method is the current class corresponding byte code file , is unique.
  • If the selection is static, then the synchronization method as the lock object is .class file byte code, unique lock multiple threads is the same.
// 2.1 使用静态成员方法解决多线程中共享资源冲突的问题
/**
 * 自定义售票线程类
 * 
 * @author 
 *
 */
//同步方法
class SingleThread3 implements Runnable {

	// 共享资源,100张票
	private static int ticket = 100;

	@Override
	public void run() {
		while (true) {
			sellTicket();
			if(ticket <= 0) {
				break;
			}
		}
	}

	// 静态同步方法
	public static synchronized void sellTicket() {
		if (ticket > 0) {
			System.out.println(Thread.currentThread().getName() +
			 "售出了第" + ticket + "张票");
			ticket -= 1;

			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			System.out.println(Thread.currentThread().getName() + "售罄!!!");
		}
	}
}

public class Demo3 {
	public static void main(String[] args) {
	//使用静态同步方法
		Thread thread1 = new Thread(new SingleThread3(), "淘票票");
		Thread thread2 = new Thread(new SingleThread3(), "猫眼");
		Thread thread3 = new Thread(new SingleThread3(), "美团");

		thread1.start();
		thread2.start();
		thread3.start();
	}
}
2.2.2 non-static synchronized method
  • Non-static method using the synchronized keyword modified synchronization method is non-static, non-static lock object synchronization method is the current class object - the this .
  • If a non-static synchronized method, then, need to ensure that the thread class object code is executed only one goal, because the lock object for the current class object.
// 2.2 使用静态成员方法解决多线程中共享资源冲突的问题
/**
 * 自定义售票线程类
 * 
 * @author 
 *
 */
//同步方法
class SingleThread3 implements Runnable {

	// 共享资源,100张票
	private static int ticket = 100;

	@Override
	public void run() {
		while (true) {
			sellTicket();
			if(ticket <= 0) {
				break;
			}
		}
	}
	
	//非静态同步方法
	public synchronized void sellTicket() {
		if (ticket > 0) {
			System.out.println(Thread.currentThread().getName() +
			 "售出了第" + ticket + "张票");
			ticket -= 1;

			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			System.out.println(Thread.currentThread().getName() +
			 "售罄!!!");
		}
	}

}

public class Demo3 {
	public static void main(String[] args) {
		//使用非静态同步方法
		//使用同一个目标代码对象
		SingleThread3 singleThread3 = new SingleThread3();
		Thread thread1 = new Thread(singleThread3,"淘票票");
		Thread thread2 = new Thread(singleThread3,"猫眼");
		Thread thread3 = new Thread(singleThread3,"美团");
	}
}
2.3 Lock Lock
  1. Object operation: Lock lock = new ReentramtLock ();
  2. Lock: lock.lock ();
  3. Unlock: lock.unlock ();
// 使用静态Lock锁解决共享资源冲突的问题
/**
 * 自定义售票线程类
 * 
 * @author 
 *
 */
//lock加锁操作
class SingleThread4 implements Runnable {

	// 共享资源,100张票
	private static int ticket = 100;
	
	//创建锁对象,这里使用的是静态的方式,锁对象是唯一的
	static Lock lock = new ReentrantLock();

	@Override
	public void run() {
		while (true) {
				
			//加锁
			lock.lock();
				if (ticket > 0) {
					System.out.println(Thread.currentThread().getName() +
					 "售出了第" + ticket + "张票");
					ticket -= 1;

					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					System.out.println(Thread.currentThread().getName() +
					 "售罄!!!");
					break;
				}
			lock.unlock();
		}
	}
}

public class Demo4 {
	public static void main(String[] args) {
		Thread thread = new Thread(new SingleThread4(), "淘票票");
		Thread thread2 = new Thread(new SingleThread4(), "猫眼");
		Thread thread3 = new Thread(new SingleThread4(), "美团");

		thread.start();
		thread2.start();
		thread3.start();
	}
}
Published 16 original articles · won praise 19 · views 6042

Guess you like

Origin blog.csdn.net/cccccv_/article/details/104738299