Java Thread

一、Suspend, resume, and stop a thread:

  1.1 java 1.5以前的實現方式:html

class MyThread implements Runnable {
  Thread thrd;  boolean suspended;  boolean stopped;

  MyThread(String name) {
    thrd = new Thread(this, name);
    suspended = false;
    stopped = false;
    thrd.start();
  } 
   public void run() {  
     try {     
      for (int i = 1; i < 10; i++) {
        System.out.print(".");
        Thread.sleep(50);     
           synchronized (this) {   
            while (suspended)
            wait();    
            if (stopped)
            break;
        }
      }
    } catch (InterruptedException exc) {
      System.out.println(thrd.getName() + " interrupted.");
    }
    System.out.println("\n" + thrd.getName() + " exiting.");
  }  
  synchronized void stop() {
    stopped = true;
    suspended = false;
    notify();
  }  
  synchronized void suspend() {
    suspended = true;
  } 
   synchronized void resume() {
    suspended = false;
    notify();
  }
}
public class Main {  
  public static void main(String args[]) throws Exception {
    MyThread mt = new MyThread("MyThread");
    Thread.sleep(100);
    mt.suspend();
    Thread.sleep(100);

    mt.resume();
    Thread.sleep(100);

    mt.suspend();
    Thread.sleep(100);

    mt.resume();
    Thread.sleep(100);

    mt.stop();
  }
}

原文地址:http://www.java2s.com/Tutorial/Java/0160__Thread/Suspendresumeandstopathread.htmjava

      1.2  java 1.5以後的實現方式:ide

用ReentrantLock,請參考ThreadPoolExecutor源代碼中所提供的例子。很經典。this

個人實現:spa

package com.io.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class C {

	/**
	 * @descreption:
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		MyRunnable myRunnable = new MyRunnable();
		ExecutorService executorService = Executors.newFixedThreadPool(1);
		executorService.execute(myRunnable);

		Thread.sleep(5000);
		//myRunnable.suspend();
		myRunnable.setSuspend(true);
		System.out.println("暫停5s...");
		Thread.sleep(5000);
		//myRunnable.resume();
		myRunnable.setSuspend(false);
		System.out.println("繼續...");

	}

	public static class MyRunnable implements Runnable {

		/**
		 * 是否暫停
		 */
		private boolean isSuspend;
		private ReentrantLock lock;
		private Condition isSuspendCondition;

		MyRunnable() {
			lock = new ReentrantLock();
			isSuspendCondition = lock.newCondition();
		}

		@Override
		public void run() {
			for (int i = 0; i < 50; i++) {
				lock.lock();
				try {
					if (isSuspend) {
						isSuspendCondition.await();
					}
					System.out.println(i);
					Thread.sleep(1000);
				} catch (Exception e) {
				} finally {
					lock.unlock();
				}
			}
		}

		public void setSuspend(boolean isSuspend) {
			lock.lock();
			try {
				this.isSuspend = isSuspend;
				if (!isSuspend) {
					isSuspendCondition.signal();
				}
			} catch (Exception e) {

			} finally {
				lock.unlock();
			}
		}

		// 暫停
		public void suspend() {
			lock.lock();
			isSuspend = true;
			lock.unlock();
		}

		// 繼續
		public void resume() {
			lock.lock();
			isSuspend = false;
			isSuspendCondition.signal();
			lock.unlock();
		}

	}
}

運行效果:線程

0code

1htm

2blog

3排序

4

5

6

7

8

9

暫停5s...

繼續...

10

11

12

13

14

15

16

17

18

二、先讓A線程輸出1,2,3,4,再讓B線程輸出A,B,C,D,如此循環往復5次。

package com.io.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Test {
	private static int count = 1;
	private static ReentrantLock lock;
	private static Condition jiCondition;
	private static Condition ouCondition;

	/**
	 * @descreption:
	 * @param args
	 */
	public static void main(String[] args) {

		lock = new ReentrantLock();
		jiCondition = lock.newCondition();
		ouCondition = lock.newCondition();

		ExecutorService executorService = Executors.newFixedThreadPool(2);
		executorService.execute(new A());
		executorService.execute(new B());
	}

	public static class A implements Runnable {

		@Override
		public void run() {
			lock.lock();
			try {
				while(count<=10)
				{
					if (count % 2 != 0) {// 奇數
						aWorking();
						count++;
						System.out.println("==========線程1 喚醒 線程2==========");
						ouCondition.signal();
					}else {
						System.out.println("==========線程1 await==========");
						jiCondition.await();
					}
					
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}
	}

	public static class B implements Runnable {

		@Override
		public void run() {
			lock.lock();
			try {
				while(count<=10)
				{
					if (count % 2 != 0) {// 奇數
						System.out.println("==========線程2 await==========");
						ouCondition.await();
					}else {
						bWorking();
						count++;
						System.out.println("==========線程2 喚醒 線程1==========");
						jiCondition.signal();
					}
					
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}
	}

	private static void aWorking() {
		for (int i = 1; i <= 4; i++) {
			System.out.println(i);
		}
		System.out.println("==========線程1 over==========");
	}

	private static void bWorking() {
		for (char i = 'A'; i <= 'D'; i++) {
			System.out.println(i);
		}
		System.out.println("==========線程2 over==========");
	}

}

運行效果:

1

2

3

4

==========線程1 over==========

==========線程1 喚醒 線程2==========

==========線程1 await==========

A

B

C

D

==========線程2 over==========

==========線程2 喚醒 線程1==========

==========線程2 await==========

1

2

3

4

==========線程1 over==========

==========線程1 喚醒 線程2==========

==========線程1 await==========

A

B

C

D

==========線程2 over==========

==========線程2 喚醒 線程1==========

==========線程2 await==========

1

2

3

4

==========線程1 over==========

==========線程1 喚醒 線程2==========

==========線程1 await==========

A

B

C

D

==========線程2 over==========

==========線程2 喚醒 線程1==========

==========線程2 await==========

1

2

3

4

==========線程1 over==========

==========線程1 喚醒 線程2==========

==========線程1 await==========

A

B

C

D

==========線程2 over==========

==========線程2 喚醒 線程1==========

==========線程2 await==========

1

2

3

4

==========線程1 over==========

==========線程1 喚醒 線程2==========

==========線程1 await==========

A

B

C

D

==========線程2 over==========

==========線程2 喚醒 線程1==========

二、線程池中的線程執行順序

ExecutorService pool = Executors.newFixedThreadPool(10);
for (int i = 0; i < len; i++) {        
pool.execute(new Before());
pool.execute(new MyThread());
pool.execute(new After());
} 如何讓pool中的三個線程按順序執行?謝謝

解決辦法1:用Executors.newSingleThreadPool

解決辦法2:用ThreadPoolExecutor,其中BlockQueue使用LinkedBlockingQueue(此隊列按 FIFO(先進先出)排序元素)。

注意:

一、必需要使用take()方法在獲取的時候達成阻塞結果
二、使用poll()方法將產生非阻塞效果

http://www.cnblogs.com/starcrm/p/4998067.html 

相關文章
相關標籤/搜索