項(xiàng)目中的多線程代碼

package com.geek.wonderful.filemanager.view.operation.viewhelper.smb;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.widget.TextView;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import jcifs.netbios.NbtAddress;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import com.geek.wonderful.filemanager.assistant.busevent.EventBusHelper;
import com.geek.wonderful.filemanager.assistant.constant.DataConstant;
import com.geek.wonderful.filemanager.assistant.utils.TimeUtils;
import com.geek.wonderful.filemanager.orm.dao.SmbAccount;
import com.geek.wonderful.filemanager.orm.dao.base.SmbAccountDao;
import com.geek.wonderful.filemanager.orm.helper.DbUtils;
import com.geek.wonderful.filemanager.view.customview.animation.ScanAnimation;
import com.geek.wonderful.filemanager.view.customview.bottomview.BottomViewMgr;

/**
 * Created by nizi on 2015/1/14.
 */
public class ScanLAN {

    public static final int SUBNET_IP_COUNT = 254;
    private static ScanLAN instance = null;

    private ConcurrentLinkedQueue<String> allLANQueue1 = new ConcurrentLinkedQueue<>();
    private ConcurrentLinkedQueue<String> allLANQueue2 = new ConcurrentLinkedQueue<>();

    private ConcurrentLinkedQueue<String> lanQueue = new ConcurrentLinkedQueue<>();
    private AtomicBoolean thread1Finish = new AtomicBoolean(false);
    private AtomicBoolean thread2Finish = new AtomicBoolean(false);
    private Subscription subscription;
    private long startTime = 0;
    private Subscription timer;
    private AtomicBoolean endTimer = new AtomicBoolean(false);

    private int curCheckSize = 1;
    public List<Socket> connectSocket = new ArrayList<>();

    private ScanLAN() {
    }

    public static ScanLAN getInstance() {
        if (instance == null) {
            instance = new ScanLAN();
        }
        return instance;
    }

    public void stopScan() {
        allLANQueue1.clear();
        allLANQueue2.clear();
        thread1Finish.set(false);
        thread2Finish.set(false);
        endTimer.set(false);

        if (subscription != null && subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }

        if (timer != null && timer.isUnsubscribed()) {
            timer.unsubscribe();
        }
    }

    private List<String> getUserInfo() {
        List<String> userList = new ArrayList<>();
        List<SmbAccount> list = DbUtils.getSmbAccountHelper().queryBuilder().list();
        for (SmbAccount smbAccount : list) {
            userList.add(smbAccount.getServeraddress());
        }
        return userList;
    }

    public void addAllAddress(Context context, TextView ipTv, TextView leftTimeTv, ScanAnimation scanAnimation) {
        stopScan();

        String address = getIp(context);
        List<String> userList = getUserInfo();

        for (int i = 0; i <= SUBNET_IP_COUNT; i++) {
            String cur = address + i;
            if (!userList.contains(cur)) {
                if (i % 2 != 0) {
                    allLANQueue2.add(cur);
                } else {
                    allLANQueue1.add(cur);
                }
            }
        }

        curCheckSize = userList.size();
        showTime(leftTimeTv);
        getLAN(allLANQueue1, ipTv, leftTimeTv, thread1Finish);
        getLAN(allLANQueue2, ipTv, leftTimeTv, thread2Finish);
        addressToNameMethod(scanAnimation);
    }

    private void showTime(final TextView leftTimeTv) {
        startTime = System.currentTimeMillis();
        timer = Observable.interval(500, 500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Func1<Long, Boolean>() {
                    @Override
                    public Boolean call(Long aLong) {

                        long useTime = System.currentTimeMillis() - startTime;
                        if (useTime > 0) {
                            long speed = useTime / 1000;
                            if (speed != 0 && speed % 2 == 0) {
                                leftTimeTv.setText(TimeUtils.secToTime(((SUBNET_IP_COUNT - curCheckSize) / speed)));
                            }
                        }

                        return endTimer.get();
                    }
                })
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        timer.unsubscribe();
                    }
                });
    }

    private void addressToNameMethod(final ScanAnimation scanAnimation) {

        try {
            subscription = Observable.interval(0, 70, TimeUnit.MILLISECONDS)
                    .observeOn(Schedulers.io())
                    .filter(new Func1<Long, Boolean>() {
                        @Override
                        public Boolean call(Long aLong) {
                            if (!lanQueue.isEmpty()) {
                                String rightAddress = lanQueue.poll();
                                if (null != rightAddress) {
                                    insertToDb(rightAddress);
                                }
                            }
                            return thread1Finish.get() && thread2Finish.get() && lanQueue.isEmpty();
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            subscription.unsubscribe();
                            scanAnimation.cancelAnimation();

                            endTimer.set(true);

                            EventBusHelper.refreshSpecifyFragment(DataConstant.SMB_ACCOUNT_ID);
                            BottomViewMgr.hideBottomView();

                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            try {
                                Thread.sleep(500);
                                subscription.unsubscribe();
                                scanAnimation.cancelAnimation();

                                endTimer.set(true);

                                EventBusHelper.refreshSpecifyFragment(DataConstant.SMB_ACCOUNT_ID);
                                BottomViewMgr.hideBottomView();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            subscription.unsubscribe();
        }

    }

    private void getLAN(ConcurrentLinkedQueue<String> allLANQueue, final TextView ipTv, final TextView leftTimeTv, final AtomicBoolean finished) {

        Observable.from(allLANQueue)
                .observeOn(Schedulers.newThread())
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String address) {
                        boolean result = false;
                        try {
                            if (address != null) {
                                Socket socket = new Socket();
                                SocketAddress socketAddress = new InetSocketAddress(address, 139);
                                socket.connect(socketAddress, 100);
                                result = true;
                                connectSocket.add(socket);
                            }
                        } catch (Exception e) {
                            result = false;
                            e.printStackTrace();
                        }

                        if (result) {
                            lanQueue.add(address);
                        }
                        curCheckSize += 1;
                        return address;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
                        finished.set(true);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String address) {
                        ipTv.setText(address);
//                        int percent = (curCheckSize * 100) / SUBNET_IP_COUNT;

                    }
                });
    }

    private String getIp(Context context) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        //檢查Wifi狀態(tài)
        if (!wm.isWifiEnabled())
            wm.setWifiEnabled(true);
        WifiInfo wi = wm.getConnectionInfo();
        //獲取32位整型IP地址
        int ipAdd = wi.getIpAddress();
        //把整型地址轉(zhuǎn)換成“*.*.*.*”地址
        String ip = intToIp(ipAdd);
        ip = ip.substring(0, ip.lastIndexOf(".") + 1);
        return ip;
    }

    private String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

    public synchronized void insertToDb(String address) {
        final SmbAccount smbAccount = new SmbAccount();
        try {
            NbtAddress nbt = NbtAddress.getByName(address);
            if (nbt != null && nbt.isActive()) {
                NbtAddress[] all = NbtAddress.getAllByAddress(nbt);
                for (NbtAddress n : all) {
                    if (!n.isGroupAddress() && n.getNameType() == 0) {
                        if (n.getHostName() != null) {
                            smbAccount.setPcname(n.getHostName());
                        }
                    }
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return;
        }
        smbAccount.setServeraddress(address);
        smbAccount.setIsscan("true");
        smbAccount.setIslogin("false");
        smbAccount.setAnonymous("true");
        smbAccount.setLoginTime(TimeUtils.getCurrentTime());

        SmbAccount account = DbUtils.getSmbAccountHelper().queryBuilder()
                .where(SmbAccountDao.Properties.Serveraddress.eq(address),
                        SmbAccountDao.Properties.Anonymous.eq("true")).unique();

        if (account == null) {
            DbUtils.getSmbAccountHelper().save(smbAccount);
        }
    }

}
package com.geek.wonderful.filemanager.assistant.searchengine.implement;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

import com.geek.wonderful.filemanager.assistant.searchengine.SearchEngine;
import com.geek.wonderful.filemanager.assistant.searchengine.SearchResultHelper;


public class SQLEngine extends EngineBase implements SearchEngine {
    private ConcurrentLinkedQueue<File> qualifiedFileQueue = new ConcurrentLinkedQueue<>();
    private SearchResultHelper mResultHelper;

    private ArrayList<AtomicBoolean> mFinishFlags;
    private ExecutorService mService;
    private int mThreadNum;
    private boolean mContainFile;

    public SQLEngine(SearchResultHelper resultHelper, int threadNum, boolean containFile) {
        this.mResultHelper = resultHelper;
        this.mThreadNum = threadNum;
        this.mService = Executors.newCachedThreadPool();
        this.mContainFile = containFile;

        mFinishFlags = new ArrayList<>();
        for (int index = 0; index < threadNum; index++) {
            mFinishFlags.add(new AtomicBoolean(false));
        }
    }

    @Override
    public void indexFiles(File rootFile) throws Exception {
        if (rootFile.exists()) {
            List<Object> fileList = new ArrayList<>();
            File[] files = rootFile.listFiles();
            for (File file : files) {
                if (!blackList.contains(file.getName().toLowerCase())) {
                    addToContentList(file, fileList);
                }
            }

            mResultHelper.batchInsert(fileList);

            for (int index = 0; index < mThreadNum; index++) {
                mService.execute(new SearchThread(index));
            }
        }
    }

    private void addToContentList(File file, List<Object> contentList) {
        if (isQualified(file)) {
            Object object = mResultHelper.getContentObject(file);
            if (object != null) {
                contentList.add(object);
            }
        }
    }

    protected boolean isQualified(File file) {
        if (file.isDirectory()) {
            qualifiedFileQueue.add(file);
            return true;
        } else {
            return mContainFile;
        }
    }

    @Override
    public void stopSearch() throws Exception {
        qualifiedFileQueue.clear();
        mService.shutdownNow();
    }

    @Override
    public void onStart() throws Exception {
    }

    private class SearchThread implements Runnable {

        private int mIndex;

        public SearchThread(int index) {
            this.mIndex = index;
        }

        @Override
        public void run() {
            indexFilesMethod();
            mFinishFlags.get(mIndex).set(true);

            while (true) {
                int allFinished = 0;
                for (int index = 0; index < mThreadNum; index++) {
                    allFinished += mFinishFlags.get(index).get() ? 1 : 0;
                }

                if (allFinished == mThreadNum) {
                    break;
                } else {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        private void indexFilesMethod() {
            List<Object> contentList = new ArrayList<>();
            int length;
            int index;

            while (!qualifiedFileQueue.isEmpty()) {
                File dir = qualifiedFileQueue.poll();
                if (dir == null) {
                    continue;
                }

                File[] files = dir.listFiles();
                if (null == files || files.length == 0) {
                    continue;
                }

                length = files.length;
                for (index = 0; index < length / 4; index += 4) {
                    addToContentList(files[index], contentList);
                    addToContentList(files[index + 1], contentList);
                    addToContentList(files[index + 2], contentList);
                    addToContentList(files[index + 3], contentList);
                }

                for (; index < length; index++) {
                    addToContentList(files[index], contentList);
                }

                if ((contentList.size() + 1) % 25 == 0) {

                    mResultHelper.batchInsert(contentList);
                    contentList.clear();

                    try {
                        Thread.sleep(150);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }

            if (!contentList.isEmpty()) {
                mResultHelper.batchInsert(contentList);
            }
        }
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子幽歼,更是在濱河造成了極大的恐慌只怎,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,126評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)声搁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來捕发,“玉大人疏旨,你說我怎么就攤上這事∨乐瑁” “怎么了充石?”我有些...
    開封第一講書人閱讀 152,445評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵,是天一觀的道長霞玄。 經(jīng)常有香客問我骤铃,道長,這世上最難降的妖魔是什么坷剧? 我笑而不...
    開封第一講書人閱讀 55,185評(píng)論 1 278
  • 正文 為了忘掉前任惰爬,我火速辦了婚禮,結(jié)果婚禮上惫企,老公的妹妹穿的比我還像新娘撕瞧。我一直安慰自己陵叽,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評(píng)論 5 371
  • 文/花漫 我一把揭開白布丛版。 她就那樣靜靜地躺著巩掺,像睡著了一般。 火紅的嫁衣襯著肌膚如雪页畦。 梳的紋絲不亂的頭發(fā)上胖替,一...
    開封第一講書人閱讀 48,970評(píng)論 1 284
  • 那天,我揣著相機(jī)與錄音豫缨,去河邊找鬼独令。 笑死,一個(gè)胖子當(dāng)著我的面吹牛好芭,可吹牛的內(nèi)容都是我干的燃箭。 我是一名探鬼主播,決...
    沈念sama閱讀 38,276評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼舍败,長吁一口氣:“原來是場噩夢啊……” “哼招狸!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起瓤湘,我...
    開封第一講書人閱讀 36,927評(píng)論 0 259
  • 序言:老撾萬榮一對(duì)情侶失蹤瓢颅,失蹤者是張志新(化名)和其女友劉穎恩尾,沒想到半個(gè)月后弛说,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,400評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡翰意,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評(píng)論 2 323
  • 正文 我和宋清朗相戀三年木人,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片冀偶。...
    茶點(diǎn)故事閱讀 37,997評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡醒第,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出进鸠,到底是詐尸還是另有隱情稠曼,我是刑警寧澤,帶...
    沈念sama閱讀 33,646評(píng)論 4 322
  • 正文 年R本政府宣布客年,位于F島的核電站霞幅,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏量瓜。R本人自食惡果不足惜司恳,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望绍傲。 院中可真熱鬧扔傅,春花似錦耍共、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至荠耽,卻和暖如春鹏往,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背骇塘。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評(píng)論 1 260
  • 我被黑心中介騙來泰國打工伊履, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人款违。 一個(gè)月前我還...
    沈念sama閱讀 45,423評(píng)論 2 352
  • 正文 我出身青樓唐瀑,卻偏偏與公主長得像,于是被迫代替她去往敵國和親插爹。 傳聞我的和親對(duì)象是個(gè)殘疾皇子哄辣,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容