当前位置:网站首页>Episode 3: thread synchronization using thread lock

Episode 3: thread synchronization using thread lock

2022-06-25 23:29:00 Guitingting

Catalog

Programming requirements

Main idea

Code implementation


Programming requirements

Please read the code on the right , Follow the tips in the method , stay Begin - End Code supplement within the area .
Test instructions

Make the program output the following results ( Because the execution order of threads is random, you may need to evaluate it many times ):

Thread-0 Got the lock.
1
2
3
4
5
Thread-0 Lock released
Thread-1 Got the lock.
6
7
8
9
10
Thread-1 Lock released
Thread-2 Got the lock.
11
12
13
14
15
Thread-2 Lock released

This level is a bit of a pit !!!

The following is the code I wrote. It can pass the self-test only once !

Main idea

When thread one runs , Let the main thread take a break , Wait for the child thread to finish executing , Start other threads .

Code implementation

package step3;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Task {
	public static void main(String[] args) {
		final Insert insert = new Insert();
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				insert.insert(Thread.currentThread());
			}
		});
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				insert.insert(Thread.currentThread());
			}
		});
		Thread t3 = new Thread(new Runnable() {
			public void run() {
				insert.insert(Thread.currentThread());
			}
		});
	//	 Set thread priority 
		// t1.setPriority(Thread.MAX_PRIORITY);
		// t2.setPriority(Thread.NORM_PRIORITY);
		// t3.setPriority(Thread.MIN_PRIORITY);

		t1.start();
        try {

        Thread.sleep(100);

        } 
        catch (InterruptedException e) {
        e.printStackTrace();
        }
		t2.start();
         try {

        Thread.sleep(100);

        } 
        catch (InterruptedException e) {
        e.printStackTrace();
        }
		t3.start();

	}
}
class Insert {
	public static int num;
	//  Defined here Lock
	private Lock lock = new ReentrantLock(); 
	public void insert(Thread thread) {
		/********* Begin *********/
		if(lock.tryLock()){
			try{
				System.out.println(thread.getName()+" Got the lock. ");
				for (int i = 0; i < 5; i++) {
					num++;
					System.out.println(num);
				}
			}finally{
				System.out.println(thread.getName()+" Lock released ");
				lock.unlock();
			}
		}else{
			System.out.println(thread.getName()+" Lock acquisition failed ");
		}
	}
		/********* End *********/
}

原网站

版权声明
本文为[Guitingting]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206252000351125.html