项目中的多线程代码

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状态
        if (!wm.isWifiEnabled())
            wm.setWifiEnabled(true);
        WifiInfo wi = wm.getConnectionInfo();
        //获取32位整型IP地址
        int ipAdd = wi.getIpAddress();
        //把整型地址转换成“*.*.*.*”地址
        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);
            }
        }
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,530评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,403评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,120评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,770评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,758评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,649评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,021评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,675评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,931评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,751评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,410评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,004评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,969评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,042评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,493评论 2 343

推荐阅读更多精彩内容