java 라인의 전면적인 설명

22335 단어 java 스레드
라인의 사용은 개발 과정에서 어디에나 있고 장면이 특히 많다고 할 수 있다.물론 통제하기 힘들죠.물론 네가 잘 놀아야 하는 것도 좋은 것이다.
간단하게 말하자면 라인은 본질적으로 프로그램의 운행을 가속화할 수 없다(물론 다중cpu의 기계는 예외이다). 단지 시간 스케줄링을 최적화할 뿐이고 우리가 보기에 전체적으로 좀 빠르다.그러나 온라인 스레드 사이의 전환이 너무 많은 정력을 소모하여 전체 프로그램의 운영 효율을 떨어뜨릴 수도 있기 때문에 왜 다중 스레드가 있는 상황에서 끊임없이 시도하고 가장 좋은 스레드 수를 찾아야 하는지, 바로 이 이치이다.그러나 다중 스레드 운행은 뚜렷한 장점이 있다. (프로그램이 빨라졌든 느려졌든) 그것은 사용자에게 있어서 사용자에 대한 대기 시간을 줄이는 것이다. 그렇지 않으면 단거리 달리기 임무를 수행하면 사용자가 직면할 수 있는 것은 바로 순간적으로 끊기고 죽는 프로그램이다(인터페이스에서 처리하지 마라).
다음은 코드로 라인에 대한 기본 지식을 설명하는데 여기는 설명이 비교적 많지만 기본적으로 작업 중의 응용을 커버할 수 있다.
package com.wxshi.thread;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *      ,                    
 *
 * @author wxshi
 *
 */
public class TraditionalThread {

	// -----------         ,           -----------

	/**
	 *         :public class ChildThread extends Thread(){}
	 *   Thread    Thread run()  ,            
	 */
	public void thread_init1() {
		Thread thread = new Thread() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(1000);
						System.out.println(Thread.currentThread().getName());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		thread.start();
	}

	/**
	 *          :Thread thread = new Thread(Runnable runnable);
	 *       run()     Runnable  ,         。
	 * Thread        Runnable  run()         ,       
	 *
	 */
	public void thread_init2() {
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(1000);
					System.out.println(Thread.currentThread().getName());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});

		thread.start();
	}

	/**
	 *   :ruannable()     run     Thread(  ),             
	 *              run  ,     Thread(  ) run  ,     ,     。
	 * */

	// -----------        ,quartz   -----------

	/**
	 *                      quartz  api      ,       
	 *
	 **/
	public void thread_traditionTimerTask() {
		Timer task = new Timer();

		// 10s        ,     
		task.schedule(new TimerTask() {
			@Override
			public void run() {
				System.out.println("task start");
			}
		}, 10000);

		// 10s        ,   5s    
		task.schedule(new TimerTask() {
			@Override
			public void run() {
				System.out.println("task start");
			}
		}, 10000, 5000);
	}

	// -----------      ,    -----------

	OutPrint out = new OutPrint();

	/**
	 *       ,                 ,                            ,          ,       
	 *
	 */
	public void thread_sync1() {

		// 10           ,               
		for (int i = 0; i < 10; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(500);
						out.print1("shiwenxue");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
	}

	/**
	 *    。        str   
	 */
	static class OutPrint {

		String lock = ""; //        ,      。

		/**
		 *             ,         ,                          
		 *              ,       
		 *
		 * @param str
		 */
		public void print1(String str) {

			//       ,             
			// this         ,    ,        ,          
			// synchronized (lock) lock            ,       。

			synchronized (this) {
				for (char c : str.toCharArray()) {
					System.out.print(c);
				}
				System.out.println();
			}
		}

		/**
		 *       ,         ,                          
		 *   :            , print1     ,            (     ,       )   ,print1
		 *     lock(   string), print2   this,    
		 *
		 * @param str
		 */
		public synchronized void print2(String str) {
			for (char c : str.toCharArray()) {
				System.out.println(c);
			}
		}

		/**
		 *        ,    print1,print2      ,        OutPrint.class     
		 *            ,       (OutPrint.class)          。
		 *
		 * @param str
		 */
		public static synchronized void print3(String str) {
			for (char c : str.toCharArray()) {
				System.out.println(c);
			}
		}
	}

	/**
	 * java5         Lock,        (         )
	 */
	class output2 {

		//    
		Lock lock = new ReentrantLock();

		/**
		 *         
		 *
		 * @param str
		 */
		public void print1(String str) {
			lock.lock(); //         
			try {
				for (char c : str.toCharArray()) {
					System.out.println(c);
				}
			} finally { //             ,      
				lock.unlock();//    ,
			}
		}
	}

	/**
	 *                 :
	 *   :          ,    ;
	 *   :        ,       
	 */
	class MyCache {

		//   map
		private Map myCache = new HashMap();

		//    
		private ReadWriteLock rwLock = new ReentrantReadWriteLock();

		//     ,          ,           
		public Object getData(String key) {
			rwLock.readLock().lock(); //    ,     ,       
			Object value = null;
			try {
				value = myCache.get(key);
				//         ,            ,     
				//        ,   ,                
				if (null == value) {
					rwLock.readLock().unlock();//     
					rwLock.writeLock().lock();//    
					try {
						if (null == value) { //                         
							value = ""; //        
						}
					} finally {
						rwLock.writeLock().unlock();//        ,    ,    
					}
				}
			} finally {
				rwLock.readLock().unlock();//     
			}
			return value;
		}
	}

	// -----------       -----------

	/**
	 *      ,         :     10 ,     20 ,    ,    100 
	 */
	public void thread_communication() {

		final Business business = new Business();

		//      
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 100; i++) {
					business.subBusiness(); //      
				}

			}
		}).start();

		//           
		for (int i = 0; i < 100; i++) {
			business.mainBusiness(); //      
		}
	}

	/**
	 *    ,               ,         ,       
	 *
	 * @author wxshi
	 *
	 */
	class Business {

		//     ,         ,      
		private boolean isTimeForSub = true;

		/**
		 *      ,  10               ,       
		 */
		public synchronized void subBusiness() {

			//   false,      
			while (!isTimeForSub) {
				try {
					this.wait();//       
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			//   true,     
			for (int i = 0; i < 10; i++) {
				System.out.println("sub loop times: " + i);
			}

			isTimeForSub = false; //    10 ,     false
			this.notify(); //       (      )
		}

		/**
		 *      ,  20 
		 */
		public synchronized void mainBusiness() {
			//   true,      
			while (isTimeForSub) {
				try {
					this.wait();//       
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			//   false,     
			for (int i = 0; i < 20; i++) {
				System.out.println("main loop times: " + i);
			}

			isTimeForSub = true; //    20 ,     true
			this.notify(); //       
		}
	}

	/**
	 *    ,               ,         ,       
	 *           Business  ,       Condition         ,      wait()   notify();
	 *   :Condition Lock    
	 *
	 * @author wxshi
	 *
	 */
	class Business2 {

		//     ,         ,      
		private boolean isTimeForSub = true;

		//    
		Lock lock = new ReentrantLock();
		//   Condition
		Condition condition = lock.newCondition();

		/**
		 *      ,  10               ,       
		 */
		public void subBusiness() {

			//   false,      
			while (!isTimeForSub) {
				try {
					// this.wait();//       
					condition.await(); //    await();    
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			//   true,     
			for (int i = 0; i < 10; i++) {
				System.out.println("loop times: " + i);
			}

			isTimeForSub = false; //    10 ,     false
			// this.notify(); //       (      )
			condition.signal(); //       (      )
		}

		/**
		 *      ,  20 
		 */
		public synchronized void mainBusiness() {
			//   true,      
			while (isTimeForSub) {
				try {
					// this.wait();//       
					condition.await(); //    await();    
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			//   false,     
			for (int i = 0; i < 20; i++) {
				System.out.println("loop times: " + i);
			}

			isTimeForSub = true; //    20 ,     true
			// this.notify(); //       
			condition.signal(); //       (      )
		}
	}

	/**
	 *       Condition            Condition                ,      
	 *         javaAPI   ,          ,     
	 *              
	 */
	class MyQueue {
		final Lock lock = new ReentrantLock();
		final Condition notFull = lock.newCondition();
		final Condition notEmpty = lock.newCondition();

		//     ,     100
		final Object[] queue = new Object[100];
		int putIndex, getIndex, count;

		//   
		public void put(Object x) throws InterruptedException {
			lock.lock();
			try {
				//       , notFull   
				while (count == queue.length) {
					notFull.await();
				}
				if (++putIndex == queue.length) {
					putIndex = 0; //           ,         
				}
				count++; //        ,        
				notEmpty.signal();
			} finally {
				lock.unlock();
			}
		}

		//   
		public Object get() throws InterruptedException {
			lock.lock();
			try {
				//          , notEmpty   
				while (count == 0) {
					notEmpty.await();
				}
				Object x = queue[getIndex]; //   
				if (++getIndex == queue.length) {
					getIndex = 0; //           ,         
				}
				count--; //         ,      
				notFull.signal(); //       ,     
				return x;
			} finally {
				lock.unlock();
			}
		}
	}

	// -----------         ,         -----------

	/**
	 *       ThreadLocal  ,  :          ,       ThreadLocal
	 *    ThreadLocal        ,           (             ,    ThreadLocal     )
	 */
	private static ThreadLocal threadData = new ThreadLocal();

	/**
	 *       ThreadLocal    ,                      ,      map               
	 *        ThreadLocal      ,              ,    
	 */
	public void thread_dataLocal() {

		//       ,          ,            
		//                   
		for (int i = 0; i < 2; i++) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					int data = new Random().nextInt();
					System.out.println(Thread.currentThread().getName() + " put data: " + data);
					threadData.set(data);//      ThreadLocal  ,   map    
					new GetA().get();
					new GetB().get();
				}
			}).start();
		}
	}

	/**
	 *         
	 */
	static class GetA {
		public void get() {
			int data = threadData.get();//              
			System.out.println(Thread.currentThread().getName() + " get data of A:" + data);
		}
	}

	/**
	 *   
	 */
	static class GetB {
		public void get() {
			int data = threadData.get();
			System.out.println(Thread.currentThread().getName() + " get data of B:" + data);
		}
	}

	/**
	 *                ,      ,       ThreadLocal
	 */
	static class MyThreadScopeData {

		//        
		private MyThreadScopeData() {
		};

		//     key      
		private static ThreadLocal myThreadData = new ThreadLocal();

		//        ,     ,        
		public static MyThreadScopeData getInstanceForThread() {
			MyThreadScopeData scopeData = myThreadData.get();
			if (null == scopeData) {
				scopeData = new MyThreadScopeData();
				myThreadData.set(scopeData);
			}
			return scopeData;
		}
	}

	// -----------       -----------

	/**
	 *              ,        
	 */
	public void thread_atomic() {

		//      int  ,     0
		AtomicInteger atomicInt = new AtomicInteger(0);
		atomicInt.addAndGet(2); // +2
		atomicInt.addAndGet(-2); // -2
		atomicInt.decrementAndGet(); // -1
	}

	// -----------     -----------

	/**
	 *                       ,       
	 */
	public void thread_pool() {

		//       5       (     )
		ExecutorService threadPool = Executors.newFixedThreadPool(5);

		//          ,         ,           
		ExecutorService threadPool2 = Executors.newCachedThreadPool();

		//      ,                (          )
		ExecutorService threadPool3 = Executors.newSingleThreadExecutor();

		//        ,                     ,  schedule()       
		ExecutorService threadPool4 = Executors.newScheduledThreadPool(6);

		//   10   
		for (int i = 0; i < 10; i++) {

			final int task = i; //        

			//     ,      5         
			threadPool.execute(new Runnable() {
				@Override
				public void run() {
					System.out.println(" " + task + "    " + Thread.currentThread().getName() + "  ");
				}
			});
		}
		threadPool.shutdown();//           
		threadPool.shutdownNow(); //         ,    
	}

	// -----------            -----------

	/**
	 * Callable   Future     ,        ,             API
	 */
	public void thread_callableAndFuture() {
		ExecutorService threadPool = Executors.newSingleThreadExecutor();

		//     submit            ,     Future 
		Future future = threadPool.submit(new Callable() {
			@Override
			public String call() throws Exception {
				return "call      ";
			}
		});

		try {
			String result = future.get(); //       
			System.out.println("    :" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * CompletionService       callable  , take            callable  
	 */
	public void thread_completionService() throws InterruptedException, ExecutionException {
		//       5       (     ,CompletionService               )
		ExecutorService threadPool = Executors.newFixedThreadPool(5);

		CompletionService completionService = new ExecutorCompletionService(threadPool);

		for (int i = 0; i < 10; i++) {
			final int task = i;

			completionService.submit(new Callable() {
				@Override
				public String call() throws Exception {
					return Thread.currentThread().getName() + "    :" + task;
				}
			});
		}

		//  10   
		for (int i = 0; i < 10; i++) {
			System.out.println(completionService.take().get());
			completionService.take().get();//     
		}
	}

	// -----------          ----------

	/**
	 *            ,                     。
	 *
	 * @param args
	 */
	public void thread_semaphore() {

		//    
		ExecutorService service = Executors.newCachedThreadPool();

		//   4    
		final Semaphore semaphore = new Semaphore(4);
		// final Semaphore semaphore = new Semaphore(4,true); //true:        

		//   10   ,               (     )
		for (int i = 0; i < 20; i++) {
			Runnable runnable = new Runnable() {
				@Override
				public void run() {
					try {
						semaphore.acquire(); //      ,       
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
					System.out.println("  " + Thread.currentThread().getName() + "  ,    " + (3 - semaphore.availablePermits()) + "   ");
					try {
						Thread.sleep((long) (Math.random() * 10000));
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("  " + Thread.currentThread().getName() + "    ");
					semaphore.release(); //      ,        

					System.out.println("  " + Thread.currentThread().getName() + "   ,    " + (3 - semaphore.availablePermits()) + "   ");
				}
			};
			service.execute(runnable);
		}

		try {
			Thread.sleep((long) (Math.random() * 100000));
			service.shutdown();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	// -----------    “  ”    ----------

	/**
	 * CyclicBarrier                                ,                    
	 *  :            ,            
	 */
	public void thread_cyclicBarrier() {

		ExecutorService service = Executors.newCachedThreadPool();

		//   CyclicBarrier    ,    5                    ,         
		final CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
		for (int i = 0; i < 5; i++) {
			Runnable runnable = new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep((long) (Math.random() * 10000));
						System.out.println("  " + Thread.currentThread().getName() + "        1,    " + (cyclicBarrier.getNumberWaiting() + 1) + "     ,"
								+ (cyclicBarrier.getNumberWaiting() == 4 ? "    ,    " : "      "));

						// (      )       
						cyclicBarrier.await();

						Thread.sleep((long) (Math.random() * 10000));
						System.out.println("  " + Thread.currentThread().getName() + "        2,    " + (cyclicBarrier.getNumberWaiting() + 1) + "     ,"
								+ (cyclicBarrier.getNumberWaiting() == 4 ? "    ,    " : "      "));

						// (      )       
						cyclicBarrier.await();

						Thread.sleep((long) (Math.random() * 10000));
						System.out.println("  " + Thread.currentThread().getName() + "        3,    " + (cyclicBarrier.getNumberWaiting() + 1) + "     ,"
								+ (cyclicBarrier.getNumberWaiting() == 4 ? "    ,    " : "      "));
						cyclicBarrier.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			service.execute(runnable);
		}

		service.shutdown();
		// try {
		// Thread.sleep((long)(Math.random()*10000));
		// // service.shutdown();
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }

	}

	// -----------    “   ”  ----------

	/**
	 * CountDownLatch       
	 * CountDownLatch.countDown()      1,  0 ,          ,    。               
	 *
	 * @param args
	 */
	public void thread_countDownLatch() {
		ExecutorService service = Executors.newCachedThreadPool();

		//    1:    1,         ,   countDown()  0,         
		final CountDownLatch cdOrder = new CountDownLatch(1);

		//    2:    3,       ,         ,     1,         ,         
		final CountDownLatch cdAnswer = new CountDownLatch(3);
		for (int i = 0; i < 3; i++) {
			Runnable runnable = new Runnable() {
				public void run() {
					try {
						Thread.sleep((long) (Math.random() * 10000));

						System.out.println("  " + Thread.currentThread().getName() + "       ");

						cdOrder.await();//        ,       0,     

						System.out.println("  " + Thread.currentThread().getName() + "     ");

						Thread.sleep((long) (Math.random() * 10000));

						System.out.println("  " + Thread.currentThread().getName() + "   ");

						cdAnswer.countDown(); //       ,        1

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			service.execute(runnable);
		}

		try {
			Thread.sleep((long) (Math.random() * 10000));

			System.out.println("  " + Thread.currentThread().getName() + "      ");

			cdOrder.countDown();//  1,         

			System.out.println("  " + Thread.currentThread().getName() + "     ,      ");

			cdAnswer.await();//       0,             

			System.out.println("  " + Thread.currentThread().getName() + "         ");
		} catch (Exception e) {
			e.printStackTrace();
		}
		service.shutdown();
	}

	// -----------          ----------

	/**
	 * Exchanger            ,         ,        ,             
	 *
	 * @param args
	 */
	public void thread_exchanger() {

		ExecutorService service = Executors.newCachedThreadPool();

		//    
		final Exchanger exchanger = new Exchanger();

		//        
		service.execute(new Runnable() {
			public void run() {
				try {

					String data1 = "  1   ";
					System.out.println("  " + Thread.currentThread().getName() + "     :" + data1 + "    ");
					Thread.sleep((long) (Math.random() * 10000));

					//   1    
					String data2 = (String) exchanger.exchange(data1);

					System.out.println("  " + Thread.currentThread().getName() + "      :" + data2);
				} catch (Exception e) {

				}
			}
		});

		//        
		service.execute(new Runnable() {
			public void run() {
				try {

					String data1 = "  2   ";
					System.out.println("  " + Thread.currentThread().getName() + "     :" + data1 + "    ");
					Thread.sleep((long) (Math.random() * 10000));

					//   2    
					String data2 = (String) exchanger.exchange(data1);

					System.out.println("  " + Thread.currentThread().getName() + "      :" + data2);
				} catch (Exception e) {

				}
			}
		});

		try {
			Thread.sleep((long) (Math.random() * 100000));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// -----------      ----------

	/**
	 *          ,                         ,     ,              
	 */
	public void thread_syncCollection() {

		//   Map
		Map syncMap = new ConcurrentHashMap();

		//   2
		Map map = new HashMap();
		Map syncMap2 = new ConcurrentHashMap(map);

		//   List
		List syncList = new CopyOnWriteArrayList();

		//   2
		List list = new CopyOnWriteArrayList();
		List syncList2 = new CopyOnWriteArrayList(list);

		//   Set
		Set syncSet = new CopyOnWriteArraySet();

		//   2
		Set set = new CopyOnWriteArraySet();
		Set syncSet2 = new CopyOnWriteArraySet(set);

	}

}

좋은 웹페이지 즐겨찾기