当前位置:网站首页>Multithreaded exercises

Multithreaded exercises

2022-06-23 09:40:00 Linging_ twenty-four

  1. Three threads t1、t2、t3. Ensure three threads ,t1 After the execution t2 perform ,t2 After the execution t3 perform .
 Use Semaphore
  1. Three threads t1、t2、t3. Ensure three threads ,t1,t2 After execution ,t3 Re execution .
public class Test01 {
    

    private Object obj = new Object();
	
    // Threads 1、2 After the execution , Reexecution thread 3, Use wait()、notify()
    public static void main(String[] args) {
    
        new Test01().exec();
    }

    public void exec(){
    
        new Thread(()->{
    
            synchronized (obj){
    
                try {
    
                    obj.wait();
                    System.out.println(" Threads :"+Thread.currentThread().getName()+"=> Yes ....");
                } catch (InterruptedException e) {
    
                    e.printStackTrace();
                }
            }
        },String.valueOf(3)).start();

        for (int i = 0; i < 2; i++) {
    
            final int tmp = i;
            new Thread(()->{
    
                synchronized (obj){
    
                    System.out.println(" Threads :" + Thread.currentThread().getName() + "=> Yes ....");
                    if(tmp == 1)
                        obj.notify();
                }
            },String.valueOf(i+1)).start();
        }
    }
}
public class Test02 {
    

    private CountDownLatch latch =new CountDownLatch(2);

    // Threads 1、2 After the execution , Reexecution thread 3, Use CountDownLatch
    public static void main(String[] args) {
    
        new Test02().exec();
    }

    public void exec(){
    
        new Thread(()->{
    
            try {
    
                latch.await();
                System.out.println(Thread.currentThread().getName() + "=> Yes ....");
            } catch (InterruptedException e) {
    
                e.printStackTrace();
            }
        }," Threads 3").start();

        for (int i = 0; i < 2; i++) {
    
            new Thread(()->{
    
                System.out.println(Thread.currentThread().getName() + "=> Yes ....");
                try {
    
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
    
                    e.printStackTrace();
                }
                latch.countDown();
            },String.valueOf(" Threads " + (i+1))).start();
        }
    }
}
class T1 implements Runnable{
    

	@Override
	public void run() {
    
		System.out.println("1");
	}	
}

class T2 implements Runnable{
    

	Thread father;
	
	public void set(Thread father) {
    
		this.father = father;
	}
	
	@Override
	public void run() {
    
		try {
    
			father.join();
		} catch (InterruptedException e) {
    
			e.printStackTrace();
		}
		System.out.println("2");
	}
}

class T3 implements Runnable{
    

	Thread father;
	
	public void set(Thread father) {
    
		this.father = father;
	}
	
	@Override
	public void run() {
    
		try {
    
			father.join();
		} catch (InterruptedException e) {
    
			e.printStackTrace();
		}
		System.out.println("3");
	}
}

public class Test {
    
	// Use join
	public static void main(String[] args) {
    
		T1 task1 = new T1();
		T2 task2 = new T2();
		T3 task3 = new T3();
		
		Thread t1 = new Thread(task1);
		Thread t2 = new Thread(task2);
		Thread t3 = new Thread(task3);
		
		task2.set(t1);
		task3.set(t1);
		
		t1.start();
		t2.start();
		t3.start();
	}
}
  1. Existing code simulations have produced 16 Log objects , And it needs to run 16 Seconds to print these logs , Please add 4 Thread to call parseLog() Method to print this separately 16 Log objects , The program just needs to run 4 These log objects can be printed in seconds .
public class Test {
    

    /** *  Existing code simulations have produced 16 Log objects , And it needs to run 16 Seconds to print these logs , *  Please add 4 Thread to call parseLog() Method to print this separately 16 Log objects , The program just needs to run 4 These log objects can be printed in seconds ; *  Ideas 1: * 1. take 16 Log objects are placed in the blocking queue  * 2. Turn on 4 Threads get log objects from the blocking queue to execute  * 3. The log object execution time is  1s * 4. In this way, the thread will keep running , Blocking  * *  Ideas 2: * 1. Create a 4 Thread pool of core threads  * 2. Add... To the blocking queue 16 Task of printing log objects  * 3. Execute the task of thread pool  * 4. The log object execution time is  1s * 5. In this way, the thread will be destroyed  * */
    public static void main(String[] args) {
    
        test01();   // Ideas 1 Realization 
        //test02(); // Ideas 2 Realization 
    }

    private static void test01() {
    
        long start = System.currentTimeMillis();
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(16);

        // take 16 Log objects are placed in the blocking queue 
        for (int i = 1; i <= 16; i++) {
    
            try {
    
                queue.put(" Log object :" + i);
            } catch (InterruptedException e) {
    
                e.printStackTrace();
            }
        }
        // Turn on 4 Threads get log objects from the blocking queue to execute 
        for (int i = 0; i < 4; i++) {
    
            new Thread(()->{
    
                while(true){
    
                    try {
    
                        String log = queue.take();
                        printLog(log);
                        long end = System.currentTimeMillis();
                        System.out.println((end-start) + "ms");
                    } catch (InterruptedException e) {
    
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }


    public static void test02(){
    
        long start = System.currentTimeMillis();
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(16);

        // Create a thread pool with four core threads 
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                4,
                4,
                3000,
                TimeUnit.MILLISECONDS,
                queue,
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );

        // take 16 The task of printing log objects is put into the blocking queue 
        for (int i = 0; i < 16; i++) {
    
            final String tmp = " Mission " + (i+1) + "";
            poolExecutor.execute(()->{
    
                printLog(tmp);
            });
        }
        poolExecutor.shutdown();

        // Determine whether the task of the thread pool has been completed 
        while(true){
    
            long end = System.currentTimeMillis();
            if(poolExecutor.isTerminated()){
    
                System.out.println((end-start) + "ms");
                break;
            }
        }
    }

    public static void printLog(String log){
    
        try {
    
            Thread.sleep(1000);
        } catch (InterruptedException e) {
    
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "===> Print log =========>" + log);
    }

}
  1. 10 Threads execute synchronously 10 A mission
public class Test2 {
    

    /** * 10 Threads execute synchronously 10 A mission  *  The way 1:synchronized *  The way 2:Lock *  The way 3:Semaphore * @param args */
    public static void main(String[] args) {
    
        //test01(); //synchronized
        //test02(); //Lock
        test03();     //Semaphore
    }


    public static void test01(){
    
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
        // Add tasks to the blocking queue 
        for (int i = 0; i < 10; i++) {
    
            try {
    
                queue.put(" Mission :" + (i+1));
            } catch (InterruptedException e) {
    
                e.printStackTrace();
            }
        }
        //10 Threads execute tasks sequentially 
        for (int i = 0; i < 10; i++) {
    
            new Thread(()->{
    
                synchronized (queue){
    
                    try {
    
                        String task = queue.take();
                        executeTask(task);
                    } catch (InterruptedException e) {
    
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    public static void test02(){
    
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);
        Lock lock = new ReentrantLock();
        // Add tasks to the blocking queue 
        for (int i = 0; i < 10; i++) {
    
            try {
    
                queue.put(" Mission :" + (i+1));
            } catch (InterruptedException e) {
    
                e.printStackTrace();
            }
        }
        //10 Threads execute tasks sequentially 
        for (int i = 0; i < 10; i++) {
    
            new Thread(()->{
    
                try {
    
                    lock.lock();
                    String task = queue.take();
                    executeTask(task);
                } catch (InterruptedException e) {
    
                    e.printStackTrace();
                }finally {
    
                    lock.unlock();
                }
            }).start();
        }
    }

    public static void test03(){
    
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
        Semaphore semaphore = new Semaphore(1);
        // Add tasks to the blocking queue 
        for (int i = 0; i < 10; i++) {
    
            try {
    
                queue.put(" Mission :" + (i+1));
            } catch (InterruptedException e) {
    
                e.printStackTrace();
            }
        }

        //10 Threads execute tasks sequentially 
        for (int i = 0; i < 10; i++) {
    
            new Thread(()->{
    
                try {
    
                    semaphore.acquire();
                    String task = queue.take();
                    executeTask(task);
                    semaphore.release();
                } catch (InterruptedException e) {
    
                    e.printStackTrace();
                }
            }).start();
        }

    }

    public static void executeTask(String task){
    
        System.out.println(Thread.currentThread().getName() + "==>" + task);
        try {
    
            Thread.sleep(1000);
        } catch (InterruptedException e) {
    
            e.printStackTrace();
        }
    }
}
  1. 10 Items were 20 There are more than one users snapping up , How to make the goods sell normally , Not oversold :
public class Test03 {
    

    //10 A commodity 
    private int goods = 10;
    
    public static void main(String[] args) {
    
        new Test03().exec();
    }

    public synchronized void exec(){
    
        for (int i = 0; i < 20; i++) {
    
            new Thread(()->{
    
                if(goods > 0){
    
                    System.out.println(Thread.currentThread().getName() + ", Got the first  " + goods-- + "  Tickets ");
                }
            },String.valueOf(" user " + (i+1))).start();
        }
    }
}
  1. Producer consumer issues
// data 
class Data{
    
	
	private String message;
	
	public String getMessage() {
    
		return message;
	}
	
	public void setMessage(String message) {
    
		this.message = message;
	}
}


// producer 
class Producer implements Runnable{
    

	private Data data;
	
	public Producer(Data data) {
    
		this.data = data;
	}
	
	@Override
	public void run() {
    
		int i = 0;
		while(true) {
    
			synchronized(data){
    
				// If the data is empty , Then the production data 
				if(data.getMessage() == null) {
    
					data.setMessage(i + "");
					System.out.println(" production :" + i);
					i++;
				}
				// Inform consumers of consumption after production data 
				data.notify();
				// Producers hang up 
				try {
    
					data.wait();
				} catch (InterruptedException e) {
    
					e.printStackTrace();
				}
			}
		}
	}
}

// consumer 
class Consumer implements Runnable{
    
	private Data data;
	
	public Consumer(Data data) {
    
		this.data = data;
	}
	
	public void run() {
    
		while(true) {
    
			synchronized(data) {
    
				// If the data is not empty , Consumption 
				if(data.getMessage() != null) {
    
					System.out.println(" consumption :" + data.getMessage());
					data.setMessage(null);
				}
				// End of consumption , Inform the producer to produce 
				data.notify();
				// Consumers hang up 
				try {
    
					data.wait();
				} catch (InterruptedException e) {
    
					e.printStackTrace();
				}
			}
		}
	}

}


public class Test {
    
	
	public static void main(String[] args) {
    
		Data data = new Data();
		Producer p = new Producer(data);
		Consumer c = new Consumer(data);
		
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(c);
		
		t1.start();
		t2.start();
	}
}
  1. Stop threads gracefully
class Task implements Runnable{
    
	
	private volatile boolean isFlag = true;
	
	public void stop() {
    
		this.isFlag = false;
	}
	
	public void run() {
    
		int i = 0;
		while(isFlag) {
    
			System.out.println(i++);
		}
	}
}

public class Test {
    
	// Use flag bits 
	public static void main(String[] args) throws InterruptedException {
    
		Task task = new Task();
		Thread t = new Thread(task);
		t.start();
		TimeUnit.SECONDS.sleep(1);
		task.stop();
	}
}
class Task implements Runnable{
    
	
	public void run() {
    
		int i = 0;
		while(true) {
    
			Thread t = Thread.currentThread();
			if(t.isInterrupted()) {
      // Determine whether it is in an interrupted state 
				break;
			}
			System.out.println(i++);
		}
	}
}

public class Test {
    
	// Use interrupt
	public static void main(String[] args) throws InterruptedException {
    
		Task task = new Task();
		Thread t = new Thread(task);
		t.start();
		TimeUnit.SECONDS.sleep(1);
		t.interrupt();  // interrupt 
	}
}
  1. Multi thread cyclic sequential printing :ABABABABAB, Threads A Print A, Threads B Print B.
 Use Object.wait() and notifyAll()   perhaps Lock + Condition
  1. Multi thread cyclic sequential printing :0102030405, Threads 0 Print 0, Threads 1 Print odd numbers , Threads 2 Print even numbers
 Use Object.wait() and notifyAll()   perhaps Lock + Condition

Subsequent code updates ...


shutdown and shutwdown The difference between :

  • shutdown Just set the state of the thread pool to SHUTWDOWN state , The task being carried out will continue to be carried out , If not executed, interrupt .
  • shutdownNow Set the status of the thread pool to STOP, The task being performed is stopped , If the task is not executed, it returns .

isShutDown:

  • isShutDown When calling shutdown() or shutdownNow() Method, return to true.
  • isTerminated When calling shutdown() After the method , And all submitted tasks are returned as true;
  • isTerminated When calling shutdownNow() After the method , Returned as after successful stop true;
原网站

版权声明
本文为[Linging_ twenty-four]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230929350378.html