Writing Java programs to implement multi-threaded operation of the same instance variable will cause the security problem of multi-threaded concurrency.

View this chapter

View job directory


Statement of needs:

Multi-threaded operation of the same instance variable operation will cause the security problem of multi-threaded concurrency. There are currently 3 threads representing 3 monkeys, operating an integer variable count in the class (representing the total number of flowers, 20 flowers in total). This variable represents the total number of flowers. Each time different monkeys (threads) are picked, the total number of flowers will be reduced by 1 until all flowers are picked by different monkeys and the program ends.

Realization ideas:

  1. Create the Current class in the project. In the Current class, declare the static Current type to refer to the instance variables num of current and int types, and specify the initial value of num to be 20, which represents the total number of flowers
  2. Define the fetch() method. Use synchronous code blocks in the method to lock the current object. In the synchronization code block, judge whether num is greater than 0, if it is greater than 0, output the progress of monkey picking flowers, and let num decrement
  3. Override the run() method. Create a while loop in this method, and the condition is that num is greater than 0. The fetch(String name) method is called in the loop, the currently running thread name is obtained by calling the Thread.currentThread().getName() method, and the thread name is assigned to the parameter name
  4. Create the program entry main() method, create 3 threads in this method, and set the names for these 3 threads as "monkey A", "monkey B" and "monkey C", and then call the start( ) Method, start thread

Implementation code:


public class T1 implements Runnable {
//	public static T1 t2 = new T1();
	//设置鲜花的数量为20 
	int num = 20;

	@Override
	public void run() {
		synchronized (new T1()) {
			while (num>0) {
				System.out.println("猴子"+Thread.currentThread().getName()+"\t菜花\t"+num--);
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String[] args) {
		T1 t1=new T1(); 
		Thread thread = new Thread(t1);
		Thread thread1 = new Thread(t1);
		thread1.setName("B");
		thread.setName("A");
		thread.start();
		thread1.start();
	}
}

 

Guess you like

Origin blog.csdn.net/weixin_44893902/article/details/108815665