摘要:一創建線程的方式更可以體現面向對象的思想,線程和代碼隔離二定時器代碼代碼三線程同步通信技術子線程次,然后主線程次,然后子線程次,然后主線程次。如果有多個線程同時到達點了,那這個數據要寫入多次,這是不對的實際失去
一、創建線程的方式
package cn.itcast.heima2; public class TraditionalThread { public static void main(String[] args) { // TODO Auto-generated method stub Thread thread = new Thread() { @Override public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); System.out.println(this.getName()); } } }; thread.start(); Thread thread2 = new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); } } }); thread2.start();//更可以體現面向對象的思想,線程和代碼隔離 new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("runnable:"+Thread.currentThread().getName()); } } }){ @Override public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("thread:"+Thread.currentThread().getName()); } } }.start(); } }二、定時器
代碼1:
package cn.itcast.heima2; import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; public class TraditionalTimerTest { public static void main(String[] args) { new Timer().schedule(new TimerTask() { @Override public void run() { System.out.println("OUTER:boom!"); } },10000,3000); while(true){ System.out.println(Calendar.getInstance().get(Calendar.SECOND)); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
代碼2:
package cn.itcast.heima2; import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; public class TraditionalTimerTest { static class MyTimerTask extends TimerTask{ static int count=0; @Override public void run() { // TODO Auto-generated method stub count=(count+1)%2; System.out.println("OUTER:boom!"); new Timer().schedule(new MyTimerTask(), 2000+2000*count); } } public static void main(String[] args) { new Timer().schedule(new MyTimerTask(),2000); while(true){ System.out.println(Calendar.getInstance().get(Calendar.SECOND)); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }三、線程同步通信技術
子線程10次,然后主線程100次,然后子線程10次,然后主線程100次。循環50次
package cn.itcast.heima2; public class TraditionalThreadComunication { public static void main(String[] args) { // TODO Auto-generated method stub Business business = new TraditionalThreadComunication().new Business(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i < 50; i++) { business.sub(i); } } }).start(); for (int i = 0; i < 50; i++) { business.main(i); } } class Business { private boolean bShouldSub=true; public synchronized void sub(int i) { if(!bShouldSub){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for (int j = 0; j < 10; j++) { System.out.println("sub thread sequence:" + j + " loop of " + i); } bShouldSub=false; this.notify(); } public synchronized void main(int i) { if(bShouldSub){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for (int j = 0; j < 100; j++) { System.out.println("main thread sequence:" + j + " loop of " + i); } bShouldSub=true; this.notify(); } } }四、線程范圍內共享變量的概念與作用
如下代碼中會出現問題
package cn.itcast.heima2; import java.util.HashMap; import java.util.Random; public class ThreadScopeShareData { private static int data = 0; private static HashMapthreadData = new HashMap<>(); public static void main(String[] args) { for (int i = 0; i < 2; i++) { new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub data = new Random(System.currentTimeMillis()).nextInt(); System.out.println(Thread.currentThread().getName() + " has put data :" + data); threadData.put(Thread.currentThread(), data); new A().get(); new B().get(); } }).start(); } } static class A { public void get() { int data=threadData.get(Thread.currentThread()); System.out.println("A from " + Thread.currentThread().getName() + " has put data :" + data); } } static class B { public void get() { int data=threadData.get(Thread.currentThread()); System.out.println("B from " + Thread.currentThread().getName() + " has put data :" + data); } } }
解決方法:
package cn.itcast.heima2; import java.util.HashMap; import java.util.Random; public class ThreadScopeShareData { private static int data = 0; static long[] seed = new long[] { 12345612, 654321 }; private static HashMap五、讀寫鎖技術的妙用threadData = new HashMap<>(); public static void main(String[] args) { new Thread(new ThreadScopeShareData.MyRunnable() { @Override public void run() { // TODO Auto-generated method stub data = MyRunnable.rd.nextInt(); System.out.println(Thread.currentThread().getName() + " has put data :" + data); threadData.put(Thread.currentThread(), data); new A().get(); new B().get(); } }).start(); new Thread(new ThreadScopeShareData.MyRunnable() { @Override public void run() { // TODO Auto-generated method stub data = MyRunnable.rd.nextInt(); System.out.println(Thread.currentThread().getName() + " has put data :" + data); threadData.put(Thread.currentThread(), data); new A().get(); new B().get(); } }).start(); } static class A { public void get() { int data=threadData.get(Thread.currentThread()); System.out.println("A from " + Thread.currentThread().getName() + " has put data :" + data); } } static class B { public void get() { int data=threadData.get(Thread.currentThread()); System.out.println("B from " + Thread.currentThread().getName() + " has put data :" + data); } } abstract static class MyRunnable implements Runnable { static Random rd = new Random(); public abstract void run(); } }
一個線程在寫的時候其他線程都不能打斷寫入過程,就是寫入的時候不能讀取
package cn.itcast.heima2; import java.util.Random; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockTest { static Random rd = new Random(); public static void main(String[] args) { final Queue3 q3 = new Queue3(); for (int i = 0; i < 3; i++) { new Thread() { public void run() { while (true) { q3.get(); } } }.start(); new Thread() { public void run() { while (true) { q3.put(rd.nextInt(10000)); } } }.start(); } } } class Queue3 { private Object data = null;// 共享數據,只能有一個線程能寫該數據,但可以有多個線程同時讀該數據。 ReadWriteLock rwl = new ReentrantReadWriteLock(); public void get() { rwl.readLock().lock(); try { System.out.println(Thread.currentThread().getName() + " be ready to read data!"); Thread.sleep((long) (Math.random() * 1000)); System.out.println(Thread.currentThread().getName() + " have read data :" + data); } catch (InterruptedException e) { e.printStackTrace(); } finally { rwl.readLock().unlock(); } } public void put(Object data) { rwl.writeLock().lock(); try { System.out.println(Thread.currentThread().getName() + " be ready to write data!"); Thread.sleep((long) (Math.random() * 1000)); this.data = data; System.out.println(Thread.currentThread().getName() + " have write data: " + data); } catch (InterruptedException e) { e.printStackTrace(); } finally { rwl.writeLock().unlock(); } } }
package cn.itcast.heima2; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class CacheDemo { private Mapcache = new HashMap (); public static void main(String[] args) { // TODO Auto-generated method stub } private ReadWriteLock rwl = new ReentrantReadWriteLock(); public Object getData(String key){ rwl.readLock().lock(); Object value = null; try{ value = cache.get(key); if(value == null){ rwl.readLock().unlock(); rwl.writeLock().lock();//A try{ if(value==null){//如果有多個線程同時到達A點了,那這個數據要寫入多次,這是不對的 value = "aaaa";//實際失去queryDB(); } }finally{ rwl.writeLock().unlock(); } rwl.readLock().lock(); } }finally{ rwl.readLock().unlock(); } return value; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/67508.html
摘要:在中一般來說通過來創建所需要的線程池,如高并發原理初探后端掘金閱前熱身為了更加形象的說明同步異步阻塞非阻塞,我們以小明去買奶茶為例。 AbstractQueuedSynchronizer 超詳細原理解析 - 后端 - 掘金今天我們來研究學習一下AbstractQueuedSynchronizer類的相關原理,java.util.concurrent包中很多類都依賴于這個類所提供的隊列式...
摘要:在中一般來說通過來創建所需要的線程池,如高并發原理初探后端掘金閱前熱身為了更加形象的說明同步異步阻塞非阻塞,我們以小明去買奶茶為例。 AbstractQueuedSynchronizer 超詳細原理解析 - 后端 - 掘金今天我們來研究學習一下AbstractQueuedSynchronizer類的相關原理,java.util.concurrent包中很多類都依賴于這個類所提供的隊列式...
摘要:表示的是兩個,當其中任意一個計算完并發編程之是線程安全并且高效的,在并發編程中經常可見它的使用,在開始分析它的高并發實現機制前,先講講廢話,看看它是如何被引入的。電商秒殺和搶購,是兩個比較典型的互聯網高并發場景。 干貨:深度剖析分布式搜索引擎設計 分布式,高可用,和機器學習一樣,最近幾年被提及得最多的名詞,聽名字多牛逼,來,我們一步一步來擊破前兩個名詞,今天我們首先來說說分布式。 探究...
閱讀 959·2023-04-25 23:50
閱讀 1970·2021-11-19 09:40
閱讀 602·2019-08-30 13:50
閱讀 2731·2019-08-29 17:11
閱讀 1046·2019-08-29 16:37
閱讀 2990·2019-08-29 12:54
閱讀 2798·2019-08-28 18:17
閱讀 2641·2019-08-26 16:55