Java线程间数据传递

###线程共享数据
Java中共享数据,可以使用一个共享对象,或者使用一个阻塞队列。接下来看一个日志的例子。其中主线程可以记录日志,而另外开启了一个线程进行日志输出

public class LogService {

	private final BlockingQueue<String> queue;
	
	private final LoggerThread logger;
	
	//关闭标记
	private volatile boolean isShutDown;
	
	public void start() {
		logger.start();
	}
	
	public void stop() {
		isShutDown = true;
		logger.interrupt();
	}
	
	public void log(String msg) throws InterruptedException {
		queue.put(msg);
	}

	public LogService() {
		queue = new LinkedBlockingQueue<String>();
		logger = new LoggerThread();
	}

	private class LoggerThread extends Thread {
		@Override
		public void run() {
			try {
				while (true) {
					if (isShutDown)
						break;
					System.out.println(queue.take());
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
}

###延迟处理
有时一个任务开启一个线程执行,需要等待数据返回再进行处理,但又希望主线程可以继续跑下去。这时可以使用Future进行处理。代码

public class GetData {
	
	private final ExecutorService executor = Executors.newSingleThreadExecutor();
	
	public Future<String> getData() {
		return executor.submit(new Callable<String>() {
			@Override
			public String call() throws Exception {
				System.out.println("my data!");
				return "hello world!";
			}
		});
	}
}

测试

public static void main(String[] args) throws InterruptedException, ExecutionException {
		GetData data = new GetData();
		Future<String> future = data.getData();
		
		//做其他事情
		System.out.println("do something!");
		
		String str = future.get();
		System.out.println(str);
	}

###其他参考
《Java并发编程实战》

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

久梦歌行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值