昨天做笔试题的时候遇到一个多线程的问题,需要我们创建三个线程,操作同一个String,并且依次赋值,最后打印。
操作同一个String只需要我们同步或者加锁就可以保证其原子性了,可是如何保证顺序执行呢?
一、join方法
我们来看api文档中的说明,等待本线程死亡。
也就是说,我们在其他线程run方法内部调用本线程的join方法,其他线程必须等待本线程死亡后才能继续执行后续的逻辑代码块。
public final void join()
throws InterruptedException
Waits for this thread to die.
An invocation of this method behaves in exactly the same way as the invocation
join(0)
Throws:
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
所以我们可以这么写:
final Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.print(Thread.currentThread().getName() + " 1 ");
}catc