java多线程从读取队列数据_java多线程从队列中取出数据执行

先用python实现, 把每一个要处理的参数存放到队列Queue中, 然后创建线程从队列中取出

class ThreadExecuteJob(threading.Thread):

"""Threaded Url Grab"""

def __init__(self, queue):

threading.Thread.__init__(self)

self.queue = queue

def run(self):

while 1:

i = self.queue.get()

try:

print "执行的参数" + str(i)

# 发送执行完毕信号

self.queue.task_done()

except Exception as e:

logging.warning(str(fun) + "---" + str(e.message) + "---" + str(e.args))

def execute_job_thread_pool(queue):

"""

:param queue: 队列

:param arg: 函数的参数

:return:

"""

for i in xrange(6):

t = ThreadExecuteJob(queue)

t.setDaemon(True)

t.start()

if __name__ == "__main__":

import Queue

day_q = Queue.Queue()

for i in xrange(6):

day_q.put(i)

execute_job_thread_pool(day_q)

day_q.join()

用python实现的多线程取出0-5个数打印出来。现在用java粗略实现的如下, 但是队列数据取完了主线程没有停止, 如何让主线程停止,如何像python那样队列数据取完主线程也停止

public class HelloJava8 {

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

// TODO Auto-generated method stub

BlockingQueue s = new LinkedBlockingQueue();

s.put("java");

s.put("python");

s.put("php");

s.put("c++");

s.put("c");

ArrayList threadList = new ArrayList();

Thread t1 = new Thread(new Consumer("zhangsan", s));

t1.start();

threadList.add(t1);

Thread t2 = new Thread(new Consumer("lisi", s));

t2.start();

threadList.add(t2);

Thread t3 = new Thread(new Consumer("wangwu", s));

t3.start();

threadList.add(t3);

Thread t4 = new Thread(new Consumer("afei", s));

t4.start();

threadList.add(t4);

Thread t5 = new Thread(new Consumer("jb", s));

t5.start();

threadList.add(t5);

for(Thread thread: threadList) {

thread.join();

}

System.out.println("主线程执行完毕");

}

}

class Consumer implements Runnable {

private String name;

private BlockingQueue s = null;

public Consumer(String name, BlockingQueue s) {

this.name = name;

this.s = s;

}

public void run() {

try {

while (true) {

String product = (String) s.take();

System.out.println(name + "消费(" + product.toString() + ").");

System.out.println("===============");

Thread.sleep(300);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值