繁体   English   中英

如何同时(或在关闭时)启动两个线程

[英]how to start two threads at the same time(or at the close time)

我有课堂Note和课堂Meeting Note有一个名为noteListArrayList 创建Meeting对象后,它将在noteList注册。

我只想在主类中说明可以同时(或在关闭时)创建Meeting两个对象。 我的计划是:

public class Note{
    //some field and method hier
    public void add(Meeting m){
        notes.add(m);
    }
    private  static final List<Entry> notes =
        Collections.synchronizedList(new ArrayList<Entry>());
}

public class Meeting implements Runnable{
    public Meeting(Note note_1,Note note_2,Calendar calendar){
        note_1.add(this);
        note_2.add(this);}
        //some method
    }

    public class Test implements Runnable{
        public static void main(String[] args) {
            Note note_1 = new Note();                
            Note note_2 = new Note();
            Meeting m_1 = new Meeting(note_1,note_2);
            Meeting m_2 = new Meeting(note_2,note_1)
            Thread t1 = new Thread(m_1);
            Thread t2 = new Thread(m_2)
            t1.start();
            t2.start();
        }
        //t1,t2 are two thread and they start one to one(not at the same time).

我已经读过可以使用wait()notify()notifyAll()任何地方,但它们必须在同步方法中使用。 我的程序中没有同步方法。

这就像你要开始两个线程一样接近。

你可以做的更多同步运行方法是让他们在运行方法的顶部等待CountDownLatch

这样做是为了消除创建和启动Threads(在运行方法执行之前发生的部分)的开销,也可能是一些怪异的调度奇怪。 但是,您无法保证实际执行锁存器后代码的并发性。

CountDownLatch latch = new CountDownLatch(2);

Runnable r1 = new Meeting(latch);
Runnable r2 = new Meeting(latch);


// in Meeting

private final CountDownLatch latch;

public void run(){

   latch.countDown();
   latch.await();

   // other code
}

不幸的是,有没有办法在同一时间启动两个线程。

让我解释一下:首先,序列为t1.Start(); t2.Start(); 首先用t1执行,然后执行t2。 这意味着只有线程t1 线程2 之前被调度,而不是实际启动。 这两种方法各占一小部分,因此人类观察者无法看到它们按顺序排列的事实。

更多,Java线程被安排 ,即。 被指派最终被执行。 即使你有一个多核CPU,你也不确定1)线程并行运行(其他系统进程可能会干扰)和2)线程都在调用Start()方法之后Start()

他们开始时间“接近”。 关键是你的代码没有在t1.start()处阻塞。

您可以通过在Meeting类的run()方法的顶部添加print语句,并在t2.start()之后t2.start()另一个print语句来查看此内容。 像这样的东西:

public class Meeting implements Runnable {
    private String name;
    public Meeting(String name) {
        this.name = name;
    }
    public void run() {
        System.out.println(name + " is running");
    }
}

public class Test {
    public static void main(String[] args) {
        Meeting m_1 = new Meeting("meeting 1");
        Meeting m_2 = new Meeting("meeting 2")
        Thread t1 = new Thread(m_1);
        Thread t2 = new Thread(m_2)
        t1.start();
        t2.start();
        System.out.println("this might print first!");
    }
}

// possible output:
> this might print first!
> meeting 1 is running
> meeting 2 is running

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM