在Java中同步2个线程的更简单方法? [英] Easier way to synchronize 2 threads in Java?

查看:80
本文介绍了在Java中同步2个线程的更简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定在辅助线程中执行某些代码之后,是否会在主线程中执行我的某些代码.这是我得到的:

I wan't to be sure that some piece of my code within the main thread will be executed after some piece of code executed withing the secondary thread. Here's what I got:

    final Object lock = new Object();
    final Thread t = new Thread(new Runnable() {
        public void run() {
            synchronized(lock) {
                System.out.println("qwerty");
                lock.notify();
            }
        }
    });

    synchronized(lock) {
        t.start();
        lock.wait();
    }

    System.out.println("absolutely sure, qwerty is above");

  1. 这是正确的解决方案吗?
  2. 有什么更短的方法可以做到这一点?

推荐答案

假定您的主线程需要启动辅助线程的处理,则

Assuming that your main thread needs to initiate the secondary thread's processing, an Exchanger would be the simplest solution.

如果辅助线程是独立的,则某种形式的

If the secondary thread is independent, then some form of BlockingQueue would be appropriate.

使用Exchanger的示例(具有适当的异常处理).一个Exchanger可以替换为两个队列.

An example using Exchanger (with proper exception handling). The one Exchanger could be substituted with two queues.

public static void main(String[] argv)
throws Exception
{
    final Exchanger<String> exchanger = new Exchanger<String>();
    new Thread(new Runnable() 
    {
        @Override
        public void run() 
        {
            try
            {
                String s = exchanger.exchange("");
                System.out.println(s);
                exchanger.exchange("this came from subthread");
            }
            catch (InterruptedException ex)
            {
                System.out.println("interrupted while waiting for message");
            }
        }
    }).start();

    exchanger.exchange("this came from main thread");
    String s = exchanger.exchange("");
    System.out.println(s);
}

这篇关于在Java中同步2个线程的更简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆