一个懒惰的线程

来源:互联网 发布:python自动化运维开发 编辑:程序博客网 时间:2024/04/30 01:27

package msgManager;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Future;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;


import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicNameValuePair;
import org.eclipse.jdt.internal.compiler.ast.ThisReference;

import com.dataService;
import com.sun.org.apache.xerces.internal.parsers.CachingParserPool.SynchronizedGrammarPool;

import cipherMeterial.cipherMeterial;

 


class  msgThread implements Runnable {
 private static  List<msg> msgs;
 private volatile static  boolean  isWaite=false;
 private static boolean isCreate=false;
 private static msgThread self;          
 private final String MainServerUrl="http://localhost:8088/testLogin/receiveMsg.msg";
 private final String guid="AD5978B1-5C0E-4767-9DE6-22D3472F9328";
 private msgThread(){
  msgs=Collections.synchronizedList(new ArrayList<msg>());
  self=this;
  new Thread(this).start();
 }
 public static msgThread getInstance(){
  if(isCreate)
   return null;
  else{
   isCreate=true;
   return new msgThread();
  }
  
 }

 public static void putMsg(msg msg){
  synchronized(msgs){
   msgs.add(msg);
  }
  if(isWaite==true){
   isWaite=false;
   synchronized (self) {
    self.notify();
   }
  }
 }

 @SuppressWarnings("static-access")
 public void run() {
  msg e=null;
  CloseableHttpAsyncClient httpclient=null;
    cipherMeterial cipher=new cipherMeterial();
          X509Certificate crt=cipher.getX509("e:\\rootca.crt");
          PrivateKey pkey=cipher.getPkcs12("e:\\issue.pfx", "123456");
  System.out.println("run start");
  while(true){
   synchronized (this) {
    while(isWaite)
     try {
      System.out.println("waiting");
      this.wait();
     } catch (InterruptedException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
     }
   }
   synchronized (msgs) {
    if(msgs.size()>0)e=msgs.remove(0);
   }
   if(e!=null){
    System.out.println("thread running "+e.content);
    /////发送的例子 应该还要对发送失败的原因做分析并做相应的处理,避免消息队列过长耗尽内存
     httpclient = HttpAsyncClients.createDefault();
     System.out.println("thread run e:"+e.content);
      try {
               // Create a local instance of cookie store
               CookieStore cookieStore = new BasicCookieStore();
              
               // Create local HTTP context
               HttpClientContext localContext = HttpClientContext.create();
               // Bind custom cookie store to the local context
               localContext.setCookieStore(cookieStore);
               Connection con=dataService.getConnection();
              
               PreparedStatement pstam=con.prepareStatement("select personid,tel from users where id=?");
               pstam.setInt(1,Integer.parseInt(e.uid));
               ResultSet rst=pstam.executeQuery();
               if(rst.next()){
                String uid=rst.getString(1)+"|"+rst.getString(2);
                HttpPost post=new HttpPost(MainServerUrl);
                String param=cipher.getEncryptMeterial(e.param, crt, pkey, "123456");
                String content=cipher.getEncryptMeterial(e.content, crt, pkey, "123456");
                uid=cipher.getEncryptMeterial(e.uid, crt, pkey, "123456");
               List<NameValuePair> params=new ArrayList<NameValuePair>();
               params.add(new BasicNameValuePair("guid",guid));
               params.add(new BasicNameValuePair("content",content));
               params.add(new BasicNameValuePair("uid",uid));
               params.add(new BasicNameValuePair("param",param));
               UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params, "utf-8");
               post.setEntity(entity);
                httpclient.start();

                // Pass local context as a parameter
                Future<HttpResponse> future = httpclient.execute(post, localContext,null);
               
                // Please note that it may be unsafe to access HttpContext instance
                // while the request is still being executed

                HttpResponse response;
       try {
        response = future.get();
        int statucode=response.getStatusLine().getStatusCode();
        if(statucode==HttpStatus.SC_OK){
         
         byte[] d=new byte[200];
         InputStream in=response.getEntity().getContent();
         in.read(d);
         String rt=new String(d,"utf-8");
         if(rt.startsWith("ok")){
          
         }else{
          //如果失败则等待重新发送
          putMsg(e);
         }
        }else{
         //如果失败则等待重新发送
         putMsg(e);
         System.out.println("send msg error rt=");
        }
       } catch (Exception e1) {
        //如果失败则等待重新发送
        putMsg(e);
        e1.printStackTrace();
       }
               }
      }catch(Exception ee){
       putMsg(e);
       ee.printStackTrace();
      }
      finally{
       try {
       httpclient.close();
      } catch (IOException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
      }
      }
    
    
    
    ////
    e=null;
   }else{
    this.isWaite=true;
   }
   System.out.println("run s");
   try {
    Thread.currentThread().sleep(1000);
   } catch (InterruptedException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
   }

  }
 }
 public static void main(String[] args){
  msgThread m=msgThread.getInstance();
  msg d=new msg();
  d.content="fsafasfsfsa";
  d.param="fsadfsafsafsafsaf";
  d.uid="p";
  Random r=new Random();
  int ii=0;
  for(;;){
   ii=r.nextInt(5);
   d.content=String.valueOf(ii);
   msgThread.putMsg(d);
   try {
    
    System.out.println("ii="+ii);
    Thread.sleep(ii*1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  
 }
}