溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

leetcode中怎么利用多線程實(shí)現(xiàn)按序打印

發(fā)布時(shí)間:2021-06-22 16:55:08 來源:億速云 閱讀:260 作者:Leah 欄目:編程語言

這篇文章給大家介紹leetcode中怎么利用多線程實(shí)現(xiàn)按序打印,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

我們提供了一個(gè)類:

public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}
三個(gè)不同的線程 A、B、C 將會(huì)共用一個(gè) Foo 實(shí)例。

一個(gè)將會(huì)調(diào)用 first() 方法
一個(gè)將會(huì)調(diào)用 second() 方法
還有一個(gè)將會(huì)調(diào)用 third() 方法
請(qǐng)?jiān)O(shè)計(jì)修改程序,以確保 second() 方法在 first() 方法之后被執(zhí)行,third() 方法在 second() 方法之后被執(zhí)行。

 

示例 1:

輸入: [1,2,3]
輸出: "firstsecondthird"
解釋: 
有三個(gè)線程會(huì)被異步啟動(dòng)。
輸入 [1,2,3] 表示線程 A 將會(huì)調(diào)用 first() 方法,線程 B 將會(huì)調(diào)用 second() 方法,線程 C 將會(huì)調(diào)用 third() 方法。
正確的輸出是 "firstsecondthird"。
示例 2:

輸入: [1,3,2]
輸出: "firstsecondthird"
解釋: 
輸入 [1,3,2] 表示線程 A 將會(huì)調(diào)用 first() 方法,線程 B 將會(huì)調(diào)用 third() 方法,線程 C 將會(huì)調(diào)用 second() 方法。
正確的輸出是 "firstsecondthird"。
 

提示:

盡管輸入中的數(shù)字似乎暗示了順序,但是我們并不保證線程在操作系統(tǒng)中的調(diào)度順序。
你看到的輸入格式主要是為了確保測(cè)試的全面性。

 實(shí)現(xiàn)方案1-鎖

package com.lau.multithread.sortprint;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 *  按序打印-實(shí)現(xiàn)方案1-鎖
 *  
	我們提供了一個(gè)類:

	public class Foo {
	  public void first() { print("first"); }
	  public void second() { print("second"); }
	  public void third() { print("third"); }
	}
	
	三個(gè)不同的線程 A、B、C 將會(huì)共用一個(gè) Foo 實(shí)例。
	
	一個(gè)將會(huì)調(diào)用 first() 方法
	一個(gè)將會(huì)調(diào)用 second() 方法
	還有一個(gè)將會(huì)調(diào)用 third() 方法
	請(qǐng)?jiān)O(shè)計(jì)修改程序,以確保 second() 方法在 first() 方法之后被執(zhí)行,third() 方法在 second() 方法之后被執(zhí)行。
 * 
 *
 */
class Foo {
	private final Lock lock = new ReentrantLock();
	
	final Condition firstCondition = lock.newCondition();
	final Condition secondCondition = lock.newCondition();
	final Condition thirdCondition = lock.newCondition();
	
	private volatile int flag = 0;
	
	public void first() { 
		try {
			lock.lock();
			
			while(this.flag != 0) {
				firstCondition.await();
			}
			
			print("first"); 
			
			flag = 1;
			
			secondCondition.signal();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	
	public void second() { 
		try {
			lock.lock();
			
			while(this.flag != 1) {
				secondCondition.await();
			}
			
			print("second"); 
			
			flag = 2;
			
			thirdCondition.signal();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	
	public void third() { 
		try {
			lock.lock();
			
			while(this.flag != 2) {
				thirdCondition.await();
			}
			
			print("third"); 
			
			flag = 0;
			
			firstCondition.signal();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	private void print(String target) {
		System.out.print(target);
	}
}


public class PrintInOrderDemo {

	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		
		Foo foo = new Foo();
		
		Map<Integer, Runnable> map = new HashMap<Integer, Runnable>() {
			{
				put(1, () -> foo.first());
				put(2, () -> foo.second());
				put(3, () -> foo.third());
			}
		};
		
		for(int i = 0; i < args.length; i++) {
			threadPool.submit(map.get(Integer.valueOf(args[i])));
		}
		
		threadPool.shutdown();
	}

}

實(shí)現(xiàn)方案2-傳統(tǒng)方式

package com.lau.multithread.sortprint;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 *  按序打印-實(shí)現(xiàn)方案2-傳統(tǒng)方式
 *  
	我們提供了一個(gè)類:

	public class Foo {
	  public void first() { print("first"); }
	  public void second() { print("second"); }
	  public void third() { print("third"); }
	}
	
	三個(gè)不同的線程 A、B、C 將會(huì)共用一個(gè) Foo 實(shí)例。
	
	一個(gè)將會(huì)調(diào)用 first() 方法
	一個(gè)將會(huì)調(diào)用 second() 方法
	還有一個(gè)將會(huì)調(diào)用 third() 方法
	請(qǐng)?jiān)O(shè)計(jì)修改程序,以確保 second() 方法在 first() 方法之后被執(zhí)行,third() 方法在 second() 方法之后被執(zhí)行。
 * 
 *
 */
class Foo2 {
	private volatile int flag = 0;
	
	public synchronized void first() { 
		try {
			while(this.flag != 0) {
				this.wait();
			}
			
			print("first"); 
			
			flag = 1;
			
			this.notifyAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public synchronized void second() { 
		try {
			while(this.flag != 1) {
				this.wait();
			}
			
			print("second"); 
			
			flag = 2;
			
			this.notifyAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public synchronized void third() { 
		try {
			while(this.flag != 2) {
				this.wait();
			}
			
			print("third"); 
			
			flag = 0;
			
			this.notifyAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void print(String target) {
		System.out.print(target);
	}
}


public class PrintInOrderDemo2 {

	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		
		Foo2 foo = new Foo2();
		
		Map<Integer, Runnable> map = new HashMap<Integer, Runnable>() {
			{
				put(1, () -> foo.first());
				put(2, () -> foo.second());
				put(3, () -> foo.third());
			}
		};
		
		for(int i = 0; i < args.length; i++) {
			threadPool.submit(map.get(Integer.valueOf(args[i])));
		}
		
		threadPool.shutdown();
	}

}

實(shí)現(xiàn)方案3-信號(hào)量

package com.lau.multithread.sortprint;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;


/**
 *  按序打印-實(shí)現(xiàn)方案3-信號(hào)量
 *  
	我們提供了一個(gè)類:

	public class Foo {
	  public void first() { print("first"); }
	  public void second() { print("second"); }
	  public void third() { print("third"); }
	}
	
	三個(gè)不同的線程 A、B、C 將會(huì)共用一個(gè) Foo 實(shí)例。
	
	一個(gè)將會(huì)調(diào)用 first() 方法
	一個(gè)將會(huì)調(diào)用 second() 方法
	還有一個(gè)將會(huì)調(diào)用 third() 方法
	請(qǐng)?jiān)O(shè)計(jì)修改程序,以確保 second() 方法在 first() 方法之后被執(zhí)行,third() 方法在 second() 方法之后被執(zhí)行。
 * 
 *
 */
class Foo3 {
	private final Semaphore firstSp = new Semaphore(1);
	private final Semaphore secondSp = new Semaphore(0);
	private final Semaphore thirdSp = new Semaphore(0);
	
	public void first() { 
		try {
			firstSp.acquire();
			
			print("first"); 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			secondSp.release();
		}
	}
	
	public void second() { 
		try {
			secondSp.acquire();
			
			print("second"); 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			thirdSp.release();
		}
	}
	
	public void third() { 
		try {
			thirdSp.acquire();
			
			print("third"); 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			firstSp.release();
		}
	}

	private void print(String target) {
		System.out.print(target);
	}
}


public class PrintInOrderDemo3 {

	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		
		Foo3 foo = new Foo3();
		
		Map<Integer, Runnable> map = new HashMap<Integer, Runnable>() {
			{
				put(1, () -> foo.first());
				put(2, () -> foo.second());
				put(3, () -> foo.third());
			}
		};
		
		for(int i = 0; i < args.length; i++) {
			threadPool.submit(map.get(Integer.valueOf(args[i])));
		}
		
		threadPool.shutdown();
	}

}

打印設(shè)置:

leetcode中怎么利用多線程實(shí)現(xiàn)按序打印leetcode中怎么利用多線程實(shí)現(xiàn)按序打印leetcode中怎么利用多線程實(shí)現(xiàn)按序打印

輸出:

firstsecondthird

關(guān)于leetcode中怎么利用多線程實(shí)現(xiàn)按序打印就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI