認識Java里面的Thread


  在一個特定的主線程執行的過程中,如果我們還需要在主線程的過程中插播一個線程,做其他動作。那么我們就可以利用Java的Thread類,創建一個新的線程。

  一:線程簡單實現的三種方式

  (1)第一種創建線程的方式是直接extends Thread 覆蓋run()方法即可。代碼如下:

  

  ------------------------------------------------------------------------------------------------

  

   運行結果:這是主線程  這是線程A

  這種實現的方式的缺點是,一個java類智能extends 繼承一個父類,有的時候不免有點尷尬。

    (2)第二種實現的方式是實現Runnable接口,實現run()方法。

  

  ---------------------------------------------------------------------------------

  

  運行結果:這是主線程 這是子線程B

  (3)第三種方式是 implements Callable,實現call()方法可以得到線程的執行結果;代碼不在寫。 

  二:什么是線程不安全

  當多個線程同時操作一個數據結構的時候產生了相互修改和串行的情況,沒有保證數據的一致性,我們同城稱這種代碼的設計為“線程不安全的”。 

  三:什么是線程安全

  保證數據的高度一致性和准確性就叫線程安全的。

  想實現線程安全大致可以有三種方法:

  (1):多例模式,也就是不用單例模式;

  (2):使用java.util.concurrent下面的類庫;

  (3):使用鎖機制synchronized,lock方式;

  四:synchronized和lock鎖機制

  (1):synchronized(同步鎖)是java關鍵字,當它用來修飾一個方法或者一個代碼塊的時候,能夠保證在同一時刻最多只有一個線程執行該代碼塊。

  聲明如下:

  public synchronized void synMethon(){

    //方法體

  }

  public int synMethod(int a1){

    synchronized(this){

    }

  } 

  (2)Lock(顯示鎖)是一個接口提供了無條件的,可輪詢的,定時的,可中斷的鎖獲取操作,所有加鎖和解鎖的方法都是顯式的。

   使用方法如下:

   class X{

     private final ReentrantLock lock = new ReentrantLock ();

     public void m(){

       lock.lock();

       try{

        方法體 

      } catch(Exception e){

         e.printStackTrace();

       }finally{

         lock.unlock()

      } 

    } 

  } 

  Lock與synchronized的比較

  a:Lock使用起來比較靈活,但必須有釋放鎖的動作配合;

  b: Lock必須手動開啟鎖和釋放鎖的動作,而synchronized則不需要手動釋放鎖和開啟鎖;

  c: Lock只適用與代碼塊加鎖,而synchronized對象之間是互斥關系; 

  使用案例:

  咖狗網中運價查詢行為分析:

  點擊“搜索”按鈕的時候,需要執行兩個動作,一個是去查詢,一個是行為分析;我們的主要目的是查詢數據,在查詢數據的同時,我們還需要進行行為分析。這個時候為了不影響功能性的操作,這個時候要啟一個子線程。主線程執行查詢功能,子線程去做行為分析。這兩個線程互不影響。並行執行,異步執行。                                            

                                           主線程

                         ————————————》 查詢功能

                                              |

                                              |

                                              |

                                       子線程(行為分析)

  比如一個接口A,B去實現這個接口,在B中:

  通過構造函數傳參 

   FreightActionCollectionForElclThread thread =  new FreightActionCollectionForElclThread(0l,0l,wxid,loadportcode,dischargeportcode,null,'B');

       啟動線程

     new Thread(thread).start();

 線程類C中實現業務邏輯:

            

 

 

public class FreightActionCollectionForElclThread implements Runnable {
private Logger logger = LoggerFactory
.getLogger(FreightActionCollectionForElclThread.class);
private HttpServletRequest request;
private char actiontype; // A整箱點擊,B整箱查詢
//微信ID
private String wxId;
//起運港
private String loadportCode;
//目的港
private String dischargeportCode;
//中轉港
private String transperport_code;
//船公司
private String carrier_enname;
 
private Long productElclId;
private Long freightElclId;
//org_id,平台ID
private Long company_id;
//產品ID
private Long product_id;
 
public FreightActionCollectionForElclThread(Long productElclId,Long freightElclId,String wxId,
String loadportCode, String dischargeportCode,
HttpServletRequest request, char actiontype) {
this.productElclId = productElclId;      //通過構造函數傳參
this.freightElclId = freightElclId;
this.request = request;
this.actiontype = actiontype;
this.loadportCode = loadportCode;
this.dischargeportCode = dischargeportCode;
this.wxId = wxId;
}
 
@Override
public void run() {
System.err.println("Thread -------------------------->:start!");
try {
String login_name ="";//通過wxid查詢login_name
long menm_id = 0l;//通過wxid查詢contract_id
PHPRPCClientService a_clientService = SpringContextHolder
.getBean("analysisPHPRPCService");
IFreightAnalysisSortService ist = a_clientService
.getPHPRPCService(IFreightAnalysisSortService.class);
 
//通過微信ID查詢會員信息
PHPRPCClientService rclientService = SpringContextHolder.getBean("mmembershipPHPRPCService");
IMemberService is = rclientService.getPHPRPCService(IMemberService.class);
Member mb = is.getByWxId(wxId);
if(mb!=null){
//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓add by liuwei 20151124 微信查詢行為采集,微信Id替換成手機號碼或者郵箱    ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  
String loginName = null;
Long orgId = mb.getPlatformId();
Long userId = mb.getUserId();
List<MemBinding> list = new ArrayList<MemBinding>();
IMemBinding memBind = rclientService.getPHPRPCService(IMemBinding.class);
list = memBind.getBindings(userId, orgId);
if(list != null && list.size()>0){
for(int i=0;i<list.size();i++){
Integer mode = list.get(i).getBindLoginMode();
if(mode != null && (mode.intValue() == 100 || mode.intValue() == 50)){
loginName = list.get(i).getBindLoginName();
}
}
}
login_name = loginName;
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑add by liuwei 20151124 微信查詢行為采集,微信Id替換成手機號碼或者郵箱 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
//login_name = mb.getLoginName();
menm_id = mb.getMembId();
}
 
//通過productEfclId,freightEfclId 查詢運價詳情
Map<String,Object>map= new HashMap<String,Object>();
map.put("productElclId",productElclId);
map.put("freightElclId",freightElclId);
PHPRPCClientService clientService = SpringContextHolder.getBean("freightElclPHPRPCService");
IFreightElclProductService service = clientService.getPHPRPCService(IFreightElclProductService.class);
FreightElclDetailsVo freightElclDetailsVo=service.getFreightElclDetailsVo(map);
 
if(freightElclDetailsVo!=null){
company_id = freightElclDetailsVo.getOrgId();
product_id = freightElclDetailsVo.getProductElclId();
loadportCode = freightElclDetailsVo.getFreightElclProduct().getLoadport();
dischargeportCode = freightElclDetailsVo.getFreightElclProduct().getDischargeport();
transperport_code = freightElclDetailsVo.getTransferport();
carrier_enname = freightElclDetailsVo.getFreightElclProduct().getCarrierEnname();
}
 
 
 
switch (actiontype) {
case 'A':
// 拼箱產品點擊行為分析
FreightPO fpo = new FreightPO();
fpo.setBi_create_time(new Date());
fpo.setBi_action_name("pm_freight_analysis_action");
fpo.setContact_id(menm_id);
fpo.setBind_login_name(login_name);
fpo.setCompany_id(company_id);
fpo.setAnalysis_freight_type("拼箱");
fpo.setProduct_id(product_id);
fpo.setLoadport_code(loadportCode);
fpo.setDischargeport_code(dischargeportCode);
fpo.setTransperport_code(transperport_code);
fpo.setCarrier_enname(carrier_enname);
fpo.setCreate_date(new Date().getTime());// 登錄時間
fpo.setReside_date(0l);// 停留時間
fpo.setSource("微信");
ist.freightActionCollectForElcl(fpo, request);
break;
case 'B':
// 拼箱產品查新行為分析
FreightQueryPO queryfpo = new FreightQueryPO();
queryfpo.setBi_create_time(new Date());// 行為應用服務器時間。
queryfpo.setBi_action_name("pm_freight_query_analysis_action");
queryfpo.setContact_id(menm_id);
queryfpo.setBind_login_name(login_name);
queryfpo.setAnalysis_freight_type("拼箱");
queryfpo.setLoadport_code(loadportCode);
queryfpo.setDischargeport_code(dischargeportCode);
queryfpo.setCarrier_enname("");
queryfpo.setQuery_date(new Date().getTime());// 行為應用服務器時間。
queryfpo.setF_num(0l);// 查詢出來 的數量
queryfpo.setSource("微信");
ist.freightQueryActionCollectForElcl(queryfpo, request);
break;
default:
break;
}
} catch (Exception e) {
logger.error("analysis failure", e);
 
}
System.err.println("Thread -------------------------->:end!");
}
 
}
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM