19.2.23-StringBuilder并不是线程安全的

2019-02-23  本文已影响0人  吹不动的林献计

示例如下代码中的加粗部分,StringBuilder在循环外:

public static void main(String[] args)throws IOException {

File file =new File("C:\\Users\\zexinlin\\Desktop\\123.csv");

    if (file.isDirectory())

{

System.out.println("文件打开失败!");

    }

File outFile =new File("C:\\Users\\zexinlin\\Desktop\\testWorst.sql");

    if(!file.exists())

   file.createNewFile();

    InputStream instream =new FileInputStream(file);

    InputStreamReader inputreader =new InputStreamReader(instream);

    BufferedReader buffreader =new BufferedReader(inputreader);

    FileOutputStream out =new FileOutputStream(outFile);

    String readline;

    int count =0;

  StringBuilder sb =new StringBuilder();

    while((readline = buffreader.readLine() )!=null){

        count++;

        StringTokenizer st =new StringTokenizer(readline,"\t",false);

        sb.append("UPDATE \n sps_active_rp_detail t \n");

        sb.append("SET \n t.`status`=0,\n ");

        sb.append("t.`update_name`=SYSDATE(),\n ");

        sb.append("t.`orderid`='',\n ");

        sb.append("t.`rp_amount`=0.00,\n ");

        sb.append("t.`order_amount`=0.00 \n ");

        sb.append("WHERE ");

        sb.append("t.`userid`='");

        sb.append(st.nextToken()+"'\n ");

        sb.append(" AND t.`orderid`='");

        sb.append(st.nextToken()+"'\n ");

        sb.append(" AND t.`status`=2;\n ");

        sb.append("\n");

        out.write(sb.toString().getBytes("utf-8"));

    }

System.out.println("Count is "+count);

    buffreader.close();

    inputreader.close();

    instream.close();

    out.close();

}

输出次数会远比count的计数大得多(16MB左右,7W多行)

而将StringBuilder包在for循环内部后,输出次数即为count的计数

上一篇 下一篇

猜你喜欢

热点阅读