Java 每日算法,三個線程按順序打印

關於多線程的基礎知識,可點擊下面鏈接進行學習。

JAVA\Android 多線程實現方式及併發與同步

 

題目1

啓動3個線程A、B、C,使A打印0,然後B打印1,然後C打印2,A打印3,B打印4,C打印5,依次類推。

public class PrintSequenceThread implements Runnable {
    private static final Object LOCK = new Object();
    /**
     * 當前即將打印的數字
     */
    private static int current = 0;
 
    /**
     * 當前線程編號,從0開始
     */
    private int threadNo;
 
    /**
     * 線程數量
     */
    private int threadCount;
 
    /**
     * 打印的最大數值
     */
    private int max;
 
    public PrintSequenceThread(int threadNo, int threadCount, int max) {
        this.threadNo = threadNo;
        this.threadCount = threadCount;
        this.max = max;
    }
 
    @Override
    public void run() {
        while(true) {
            synchronized (LOCK) {
                // 判斷是否輪到當前線程執行
                while (current % threadCount != threadNo) {
                    if (current > max) {
                        break;
                    }
                    try {
                        // 如果不是,則當前線程進入wait
                        LOCK.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // 最大值跳出循環
                if (current > max) {
                    break;
                }
                System.out.println("thread-" + threadNo + " : " + current);
                current++;
                // 喚醒其他wait線程
                LOCK.notifyAll();
            }
        }
    }
 
    public static void main(String[] args) {
        int threadCount = 3;
        int max = 10;
        for(int i=0;i<threadCount;i++) {
            new Thread(new PrintSequenceThread(i,threadCount, max)).start();
        }
    }
}

題目2

編寫一個程序,開啓 3 個線程,這三個線程的分別爲 A、B、C,每個線程打印對應的“A”、“B”、“C” 10 遍,要求輸出的結果必須按順序顯示。如:ABCABCABC…… 

*tate初始化爲1,如果state爲1執行A線程,A線程修改state爲2執行B線程;如果state爲2執行B線程,B線程修改state爲3企圖執行C線程;如果state爲3執行C線程,C線程修改state爲1,企圖執行A線程。

解法1:採用volatile修飾的全局變量state作爲條件控制,用for循環加if條件判斷的忙等模式。

package com.yangliu.lock;
 
import java.io.File;
 
public class ABC1 {
	private static int n = 100000; //控制線程執行次數
	private volatile static int state = 0; //控制線程執行條件
	static class ThreadA extends Thread {
		public void run() {
           for(int i=0;i<n;){
        	   if(state%3==0){
        		   System.out.println("A,loopNum="+i);
        		   state++;
        		   i++;
        	   }
           }
		}
	}
	static class ThreadB extends Thread {
		public void run() {
			for(int i=0;i<n;){
	        	   if(state%3==1){
	        		   System.out.println("B,loopNum="+i);
	        		   state++;
	        		   i++;
	        	   }
	           }
		}
	}
	static class ThreadC extends Thread {
		public void run() {
			for(int i=0;i<n;){
	        	   if(state%3==2){
	        		   System.out.println("C,loopNum="+i);
	        		   state++;
	        		   i++;
	        	   }
	           }
		}
	}
	public static void main(String[] args) throws InterruptedException {
	   long startTime = System.currentTimeMillis();
	   new ThreadA().start();
	   new ThreadB().start();
	   ThreadC c =new ThreadC();
 	   c.start();
 	   c.join();
	   long endTime = System.currentTimeMillis();
	   File f = new File("f.txt");
	   FileUtil.writeToFile(f, "n="+n);
	   FileUtil.writeToFile(f, "RunTime is "+(double)(endTime-startTime)/1000+"s");
	}
}

問題:爲什麼共享變量要加volatile?加volatile就足夠了嗎?

分析:因爲加volatile可以保證變量state的可見性,上一個線程對state的修改對下一個線程是可見的。另外由於有if條件做判斷,所以可以確保只有單一的線程修改變量state的值,這裏用volatile就足夠了。

解法2:採用原子類AtomicInteger來控制變量state,其他不變
 

package com.yangliu.lock;
 
import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;
 
public class ABC2 {
	private static int n = 100000; //控制線程執行次數
	private static AtomicInteger state = new AtomicInteger(0); //控制線程執行條件
	static class ThreadA extends Thread {
		public void run() {
           for(int i=0;i<n;){
        	   if(state.get()%3==0){
        		   System.out.println("A,loopNum="+i);
        		   state.getAndIncrement();
        		   i++;
        	   }
           }
		}
	}
	static class ThreadB extends Thread {
		public void run() {
			for(int i=0;i<n;){
				if(state.get()%3==1){
	        		   System.out.println("B,loopNum="+i);
	        		   state.getAndIncrement();
	        		   i++;
	        	   }
	           }
		}
	}
	static class ThreadC extends Thread {
		public void run() {
			for(int i=0;i<n;){
				if(state.get()%3==2){
	        		   System.out.println("C,loopNum="+i);
	        		   state.getAndIncrement();
	        		   i++;
	        	   }
	           }
		}
	}
	public static void main(String[] args) throws InterruptedException {
		 long startTime = System.currentTimeMillis();
		   new ThreadA().start();
		   new ThreadB().start();
		   ThreadC c =new ThreadC();
	 	   c.start();
	 	   c.join();
		   long endTime = System.currentTimeMillis();
		   File f = new File("f.txt");
		   FileUtil.writeToFile(f, "RunTime is "+(double)(endTime-startTime)/1000+"s");
	}
}

解法3:採用ReentrantLock鎖住整段代碼

package com.yangliu.lock;
 
import java.io.File;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ABC3 {
	private static int n = 100000; // 控制線程執行次數
	private static int state = 0; // 控制線程執行條件
	private static Lock lock = new ReentrantLock();
	static class ThreadA extends Thread {
		public void run() {
			for (int i = 0; i < n;) {
				lock.lock();
				if (state % 3 == 0) {
					System.out.println("A,loopNum=" + i);
					state++;
					i++;
				}
				lock.unlock();
			}
		}
	}
	static class ThreadB extends Thread {
		public void run() {
			for (int i = 0; i < n;) {
				lock.lock();
				if (state % 3 == 1) {
					System.out.println("B,loopNum=" + i);
					state++;
					i++;
				}
				lock.unlock();
			}
		}
	}
	static class ThreadC extends Thread {
		public void run() {
			for (int i = 0; i < n;) {
				lock.lock();
				if (state % 3 == 2) {
					System.out.println("C,loopNum=" + i);
					state++;
					i++;
				}
				lock.unlock();
			}
		}
	}
	public static void main(String[] args) throws InterruptedException {
		 long startTime = System.currentTimeMillis();
		 new ThreadA().start();
		 new ThreadB().start();
		 ThreadC c =new ThreadC();
	 	   c.start();
	 	   c.join();
		 long endTime = System.currentTimeMillis();
		 File f = new File("f.txt");
		 FileUtil.writeToFile(f, "RunTime is "+(double)(endTime-startTime)/1000+"s");
	}
}

解法4:採用ReentrantLock,三個Condition進行await和signal操作

public class ABC4 {
	private static int n = 100000; // 控制線程執行次數
	private static Lock lock = new ReentrantLock();
	private static Condition A = lock.newCondition();
	private static Condition B = lock.newCondition();
	private static Condition C = lock.newCondition();
	private static int state = 0;
 
	private static class ThreadA extends Thread {
		public void run() {
			lock.lock();
			try {
				for (int i = 0; i < n;i++) {
					if (state % 3 != 0)
						A.await();
					System.out.println("A,loopNum=" + i);
					state++;
					B.signal();
				}
			} catch (InterruptedException e) {
 
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
 
		}
	}
	static class ThreadB extends Thread {
		public void run() {
			lock.lock();
			try {
				for (int i = 0; i < n;i++) {
					if (state % 3 != 1)
						B.await();
					System.out.println("B,loopNum=" + i);
					state++;
					C.signal();
				}
			} catch (InterruptedException e) {
 
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
 
		}
	}
	static class ThreadC extends Thread {
		public void run() {
			lock.lock();
			try {
				for (int i = 0; i < n;i++) {
					if (state % 3 != 2)
						C.await();
					System.out.println("C,loopNum=" + i);
					state++;
					A.signal();
				}
			} catch (InterruptedException e) {
 
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
 
		}
	}
	public static void main(String[] args) throws InterruptedException {
		 long startTime = System.currentTimeMillis();
		 new ThreadA().start();
		 new ThreadB().start();
		 ThreadC c =new ThreadC();
	 	 c.start();
	 	 c.join();
		 long endTime = System.currentTimeMillis();
		 File f = new File("f.txt");
		 FileUtil.writeToFile(f, "RunTime is "+(double)(endTime-startTime)/1000+"s");
	}
}

解法5:使用信號量機制,完全不用state變量進行條件控制

public class ABC5 {
	private static int n = 100000;
    private static Semaphore AB = new Semaphore(0);
    private static Semaphore BC = new Semaphore(0);
    private static Semaphore CA = new Semaphore(0);
    
    static class ThreadA extends Thread {
 
        @Override
        public void run() {
            try {
                for (int i = 0; i < n; i++) {
                    CA.acquire();
                    System.out.println("A,loopNum=" + i);
                    AB.release();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
    }
    static class ThreadB extends Thread {
 
        @Override
        public void run() {
            try {
                for (int i = 0; i < n; i++) {
                    AB.acquire();
                    System.out.println("B,loopNum=" + i);
                    BC.release();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
    }
    static class ThreadC extends Thread {
 
        @Override
        public void run() {
            try {
                for (int i = 0; i < n; i++) {
                    BC.acquire();
                    System.out.println("C,loopNum=" + i);
                    CA.release();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
       long startTime = System.currentTimeMillis();
       CA.release(); //釋放CA,讓A線程先執行
 	   new ThreadA().start();
 	   new ThreadB().start();
 	   ThreadC c =new ThreadC();
 	   c.start();
 	   c.join();
 	   long endTime = System.currentTimeMillis();
 	   File f = new File("f.txt");
	   FileUtil.writeToFile(f, "RunTime is "+(double)(endTime-startTime)/1000+"s");
 	  
    }
}

當n取10萬時的運行時間比較:

n=100000
RunTime is 5.623s
RunTime is 5.322s
RunTime is 4.482s
RunTime is 4.279s
RunTime is 3.842s

結果可知,

第5種信號量機制運行時間最少,最佳。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章