JAVA Java多线程与并发库
生活随笔
收集整理的這篇文章主要介紹了
JAVA Java多线程与并发库
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java多線程與并發庫
同步方式
import javax.xml.stream.events.StartDocument;public class TestSynchronized {public static void main(String[] args) {// TODO Auto-generated method stubTestSynchronized test = new TestSynchronized();test.init();}void init() {final Outputer outputer = new Outputer();new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {Thread.sleep(10);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}outputer.Output("wangyuyuyuyuyuyuyuyu");}}}){}.start();new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {Thread.sleep(10);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}outputer.Output("zhouzhanzhaozhaozhaozhao");}}}){}.start();}class Outputer{final static String lockKey = "lock";//定義輸出函數//第一種方式,提供某個鎖public void Output(String name){int len = name.length();synchronized (lockKey) {for (int i = 0; i < len; i++){System.out.print(name.charAt(i));}System.out.println();}}//第二種方式,鎖住自己public void Output1(String name){int len = name.length();synchronized (this) { //也可以用Outputer.classfor (int i = 0; i < len; i++){System.out.print(name.charAt(i));}System.out.println();}}//第三種方式,函數前面加關鍵字synchronizedpublic synchronized void Output2(String name){int len = name.length();for (int i = 0; i < len; i++){System.out.print(name.charAt(i));}System.out.println();}}}定時器Timer
import java.util.Timer; import java.util.TimerTask;public class TimerTest {public static void main(String[] args){new Timer().schedule(new TimerTask(){@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("boom");}}, 3000);} }HashMap存儲線程
import java.util.HashMap; import java.util.Map; import java.util.Random;public class TestThreadMap {private static HashMap<Thread, Integer> map = new HashMap<Thread, Integer>();public static void main(String[] args) {//TestThreadMap testThreadMap = new TestThreadMap();for (int i = 0; i < 2; i++) {new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubint data = new Random().nextInt();map.put(Thread.currentThread(), data);new A().Get();new B().Get();}}){}.start();}}static class A{public void Get(){int data = map.get(Thread.currentThread());System.out.println("A from " + Thread.currentThread().getName() + " get data " + data);}}static class B{public void Get(){int data = map.get(Thread.currentThread());System.out.println("B from " + Thread.currentThread().getName() + " get data " + data);}} }ThreadLocal類似HashMap存儲線程
import java.util.HashMap; import java.util.Map; import java.util.Random;public class TestThreadMap {private static HashMap<Thread, Integer> map = new HashMap<Thread, Integer>();public static void main(String[] args) {//TestThreadMap testThreadMap = new TestThreadMap();for (int i = 0; i < 2; i++) {new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubint data = new Random().nextInt();map.put(Thread.currentThread(), data);new A().Get();new B().Get();}}){}.start();}}static class A{public void Get(){int data = map.get(Thread.currentThread());System.out.println("A from " + Thread.currentThread().getName() + " get data " + data);}}static class B{public void Get(){int data = map.get(Thread.currentThread());System.out.println("B from " + Thread.currentThread().getName() + " get data " + data);}} } import java.util.Random;public class TestThreadlocal_2 {public static void main(String[] args) {// TODO Auto-generated method stubfor (int i = 0; i < 2; i++){new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubint data = new Random().nextInt();MyData.getInstance().setName("myData" + data);MyData.getInstance().setAge(data);new A().Get();new B().Get();}}){}.start();}}static class A{public void Get(){MyData data = MyData.getInstance();System.out.println("A from " + Thread.currentThread().getName() + " get data " + data.getName() + ", " + data.getAge());}}static class B{public void Get(){MyData data = MyData.getInstance();System.out.println("B from " + Thread.currentThread().getName() + " get data " + data.getName() + ", " + data.getAge());}}}class MyData{String name;int age;public static /*synchronized*/ MyData getInstance(){MyData instance = threadLocal.get();if (instance == null){ //不存在就創建一個與本線程有關的實例對象instance = new MyData();threadLocal.set(instance);}return instance;}//private static MyData instance = null;private static ThreadLocal<MyData> threadLocal = new ThreadLocal<MyData>();public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}線程池
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;public class TestThreadPool {public static void main(String[] args){//固定大小的線程池ExecutorService threadPool = Executors.newFixedThreadPool(3);//緩存線程池,當線程不夠用時會自動增加,多了會自動減少//ExecutorService threadPool = Executors.newCachedThreadPool();//單一線程池,線程死了可以重新啟動//ExecutorService threadPool = Executors.newSingleThreadExecutor();for (int i = 1; i <= 10; i++){final int taskid = i;threadPool.execute(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubfor (int j = 1; j <= 10; j++) {System.out.println(Thread.currentThread().getName() + " is loop of " + j + " for task of " + taskid);}}});}System.out.println("all have finished");threadPool.shutdown(); //線程池里沒有任務了,線程池才關閉,等10個任務都完成后才關閉//threadPool.shutdownNow(); //一個線程完成之后立馬關閉,此時只完成了3個任務/*//定時器線程池Executors.newScheduledThreadPool(3).schedule(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("booming");}}, 6,TimeUnit.SECONDS); //多長時間后執行任務 */ Executors.newScheduledThreadPool(3).scheduleAtFixedRate( //以固定頻率執行任務new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("booming");}}, 6, //初始時間2, //間隔時間TimeUnit.SECONDS);} }鎖Lock
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;import javax.xml.stream.events.StartDocument;public class TestLock {public static void main(String[] args) {// TODO Auto-generated method stubTestLock test = new TestLock();test.init();}void init() {final Outputer outputer = new Outputer();new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {Thread.sleep(10);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}outputer.Output("wangyuyuyuyuyuyuyuyu");}}}){}.start();new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {Thread.sleep(10);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}outputer.Output("zhouzhanzhaozhaozhaozhao");}}}){}.start();}class Outputer{Lock lock = new ReentrantLock(); //鎖public void Output(String name){int len = name.length();lock.lock();try {for (int i = 0; i < len; i++){System.out.print(name.charAt(i));}System.out.println("");} finally{// TODO: handle exceptionlock.unlock();}}}}讀寫鎖ReadWriterLock
import java.util.HashMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;public class TestReadWriterLock {HashMap<String, Object> mp = new HashMap<String, Object>();private ReadWriteLock rwl = new ReentrantReadWriteLock();public Object Get(String key){rwl.readLock().lock();Object value = null;try {value = mp.get(key);if (value == null) {rwl.readLock().unlock();rwl.writeLock().lock();try {if (value == null){value = "aaa";}} finally {// TODO: handle finally clauserwl.writeLock().unlock();}rwl.readLock().lock();}} finally {rwl.readLock().unlock();}return value;} }信號燈Semaphere(控制當前運行的線程個數)
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.function.IntToDoubleFunction;public class TestSemaphere {public static void main(String[] args) {// TODO Auto-generated method stub/*1.創建線程池*2.創建信號燈,大小為3 *3.循環10次,Runnable里設置信號燈acqure*/ExecutorService es = Executors.newCachedThreadPool();Semaphore semaphore = new Semaphore(3);for(int i = 0; i < 10; i++){es.execute(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {semaphore.acquire();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}System.out.println("線程" + Thread.currentThread().getName() + "進入");try {Thread.sleep((int)Math.random() * 10000);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}System.out.println("線程" + Thread.currentThread().getName() + "即將結束");semaphore.release();System.out.println("線程" + Thread.currentThread().getName() + "已結束");es.shutdown();}});}}}數據交換Exchanger(當兩個數據都到達后才能進行交換,否則阻塞)
import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;public class TestExchanger {public static void main(String[] args) {// TODO Auto-generated method stubExecutorService es = Executors.newCachedThreadPool();Exchanger<String> exchanger = new Exchanger<String>();es.execute(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {String data1 = "x";System.out.println("線程" + Thread.currentThread().getName() + "正在把數據" + data1 + "發送出去");Thread.sleep((int)(Math.random() * 5000));String getData = exchanger.exchange(data1);System.out.println("線程" + Thread.currentThread().getName() + "接受到的數據為: " + getData);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}});es.execute(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {String data1 = "y";System.out.println("線程" + Thread.currentThread().getName() + "正在把數據" + data1 + "發送出去");Thread.sleep((int)(Math.random() * 5000));String getData = exchanger.exchange(data1);System.out.println("線程" + Thread.currentThread().getName() + "接受到的數據為: " + getData);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}});}}同步屏障CyclicBarrier(多個線程彼此等待,集合后再往后運行)
import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;public class TestCyclicBarrier {//多個線程彼此等待,集合后再運行public static void main(String[] args) {// TODO Auto-generated method stub//創建線程池和CyclicBarrier,同時運行多個線程,調用awaitExecutorService es = Executors.newCachedThreadPool();final CyclicBarrier cb = new CyclicBarrier(3);for (int i = 0; i < 3; i++){es.execute(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {Thread.sleep((int)(Math.random() * 1000));System.out.println("線程" + Thread.currentThread().getName() + "到達集合點1");System.out.println("當前有" + (cb.getNumberWaiting()+1) + "人在等待");cb.await();Thread.sleep((int)(Math.random() * 1000));System.out.println("線程" + Thread.currentThread().getName() + "到達集合點2");System.out.println("當前有" + (cb.getNumberWaiting()+1) + "人在等待");cb.await();Thread.sleep((int)(Math.random() * 1000));System.out.println("線程" + Thread.currentThread().getName() + "到達集合點3");System.out.println("當前有" + (cb.getNumberWaiting()+1) + "人在等待");cb.await();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}});}es.shutdown();}}CountDownLatch(類似倒計時計數器,當計數減為0時,所有等待者才開始執行)
import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;public class TestCountDownLatch {//類似倒計時計數器,當計數減為0的時候,所有等待者才開始執行public static void main(String[] args) {// TODO Auto-generated method stub//創建兩個計數器,一個為1,一個為3,代表一個裁判員,三個運動員,裁判員在未下達命令前運動員等待,下達命令后才執行//等三個運動員都到達終點后,裁判員才公布成績ExecutorService es = Executors.newCachedThreadPool();CountDownLatch cdOrder = new CountDownLatch(1);CountDownLatch cdAnswer = new CountDownLatch(3);for (int i = 0; i < 3; i++) {final int id = i;es.execute(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {System.out.println("運動員" + id + "正準備接受命令");cdOrder.await();System.out.println("運動員"+ id + "接受到命令");Thread.sleep((int)(Math.random() * 5000));System.out.println("運動員" + id + "到達終點");cdAnswer.countDown();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}});}try {Thread.sleep(1000);System.out.println("裁判員發出指令");cdOrder.countDown();System.out.println("裁判員等待所有運動員到達終點");cdAnswer.await();System.out.println("裁判員公布成績");} catch (Exception e) {// TODO: handle exception}}}Callable和Future
import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; 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.TimeUnit; import java.util.concurrent.TimeoutException;public class TestCallableAndFuture {public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException{ExecutorService threadPool = Executors.newSingleThreadExecutor();Future future =threadPool.submit(new Callable<String>() {@Overridepublic String call() throws Exception {// TODO Auto-generated method stubThread.sleep(2000);return "hello";}});System.out.println("得到結果: " + future.get()); //callable完成任務返回結果,由future去拿,需要等待一段時間//System.out.println("得到結果: " + future.get(1, TimeUnit.SECONDS)); //要在規定的時間內得到結果,如果得不到就拋出異常//CompletionService 用于提交一組callable任務,并用take方法得到一個已完成任務的future對象ExecutorService threadPool2 = Executors.newFixedThreadPool(10);CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);for (int i = 1; i <= 10; i++){final int taskid = i;completionService.submit(new Callable<Integer>() {@Overridepublic Integer call() throws Exception {// TODO Auto-generated method stubtry {Thread.sleep(new Random().nextInt(5000));} catch (Exception e) {// TODO: handle exception}return taskid;}});}for (int i = 1; i <= 10; i++){System.out.println(completionService.take().get());}}}阻塞隊列ArrayBlockingQueue
import java.util.concurrent.ArrayBlockingQueue;public class TestArrayBlockingQueue {//阻塞隊列當隊列為空時take會阻塞,當隊列滿時put會阻塞//用兩個阻塞隊列模擬兩個線程交替運行//兩個阻塞隊列大小均設置為1,其中一個放一個數據public static void main(String[] args) {// TODO Auto-generated method stubBusiness business = new Business();new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubfor (int j = 1; j <= 10; j++) {business.Sub(j);}}}){}.start();for (int j = 1; j <= 10; j++) {business.Main(j);}}static class Business{ArrayBlockingQueue abq1 = new ArrayBlockingQueue(1);ArrayBlockingQueue abq2 = new ArrayBlockingQueue(1);public Business() {try {abq2.put(1);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}public void Sub(int j){try {abq1.put(1);for (int i = 1; i <= 10; i++){System.out.println("sub thread " + i + " of loop " + j);}abq2.take();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}public void Main(int j){try {abq2.put(1);for (int i = 1; i <= 10; i++){System.out.println("main thread " + i + " of loop " + j);}abq1.take();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}}}練習: 子線程運行10次,主線程運行20次,交替運行
public class prictice_1 {//子線程運行10次,主線程運行20次public static void main(String[] args) {// TODO Auto-generated method stubBusiness business = new Business();new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubfor (int j = 1; j <= 10; j++) {business.Sub(j);}}}){}.start();for (int j = 1; j <= 10; j++) {business.Main(j);}}} class Business{private boolean isSub = true;public synchronized void Sub(int j){while (!isSub) {try {this.wait();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}for (int i = 1; i <= 10; i++){System.out.println("sub thread " + i + " of loop " + j);}isSub = false;this.notify();}public synchronized void Main(int j){while (isSub){try {this.wait();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}for (int i = 1; i <= 20; i++){System.out.println("main thread " + i + " of loop " + j);}isSub = true;this.notify();} }總結
以上是生活随笔為你收集整理的JAVA Java多线程与并发库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 遇到重复性电脑操作不用愁电脑自动重复操作
- 下一篇: 如何把图片转换为二维码或者链接如何把图片