如何在同一时间(或在关闭时间)启动两个线程 [英] how to start two threads at the same time(or at the close time)
问题描述
我有一个班级注意
和一个班级会议
。在类注意
中有 ArrayList
名为 noteList
。当创建会议
的对象时,它将在 noteList
中注册。
I have a class Note
and a class Meeting
. There is an ArrayList
named noteList
in class Note
. When an object of Meeting
is created it is then registered in the noteList
.
我只想在主类中说明可以同时(或在关闭时)创建 Meeting
的两个对象。我的程序是:
I just want to demostrate in the main class that two objects of Meeting
can be created at the same time (or at the close time). My program is:
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()
可以使用,但必须在同步方法中使用它们。我的程序中没有同步方法。
I have read anywhere that wait()
, notify()
or notifyAll()
can be used, but they must be used in a synchronized method. I have no synchronized methods in my program.
推荐答案
这就像你要开始两个线程一样接近。
This is as close as you are going to get to starting the two threads.
你可以做些什么来同步运行方法更多的是让他们等待 CountDownLatch 在他们的运行方法的顶部。
What you could do to synchronize the run methods even more is to have them wait on a CountDownLatch on the top of their run methods.
这是做什么的正在消除创建和启动Threads(在运行方法执行之前发生的部分)的开销,也许还有一些怪异的调度奇怪。但是,您无法保证实际执行锁存器后代码的并发性。
What this does is taking away the overhead of creating and starting Threads (the part that happens before your run method gets executed), and maybe also some freak scheduling oddities. You have no guarantee however, how concurrent the code after the latch will actually be executed.
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
}
这篇关于如何在同一时间(或在关闭时间)启动两个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!