java中一个线程等待另一个线程执行完后再执行

该问题大概有3种方法:

1.notify、wait方法,Java中的唤醒与等待方法,关键为synchronized代码块,也常用Object作为参数,示例如下。

 

package com.thread_lc;

class MyThread1 implements Runnable
{
    public int i = 10;
 
    @Override
    public void run ()
    {
        Thread currThread = Thread.currentThread ();
        synchronized (currThread)
        {
            ++i;
            System.out.println (this.getClass ().getName () + " i = " + i);
            currThread.notify ();
        }
    }
}

 

package com.thread_lc;

class MyThread2 implements Runnable
{
    @Override
    public void run ()
    {
        Thread currThread = Thread.currentThread ();
        synchronized (currThread)
        {
            while ("t1".equals (currThread.getName ()))
            {
                try
                {
                    currThread.wait (0);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace ();
                }
            }
            done ();
        }
    }
 
    public synchronized void done ()
    {
        System.out.println ("更改完毕");
    }
}

 

package com.thread_lc;

public class MyThreadMain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread1 myThread1 = new MyThread1();
		MyThread2 myThread2 = new MyThread2();
		Thread t1 = new Thread(myThread1);
		t1.setName("t1");
		t1.start();
		Thread t2 = new Thread(myThread2);
		t2.setName("t2");
		t2.start();
	}

}

 

2.CountDownLatch类

一个同步辅助类,常用于某个条件发生后才能执行后续进程。给定计数初始化CountDownLatch,调用countDown()方法,在计数到达零之前,await方法一直受阻塞。

重要方法为countdown()与await();

示例如下。

 

package com.thread_lc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test4 {

	class DTask implements Runnable {
		private CountDownLatch downLatch;

		private String name;

		public DTask(CountDownLatch downLatch, String name) {
			this.downLatch = downLatch;
			this.name = name;
		}
		
		@Override
		public void run() {
			if (name.equals("A"))
				try {
					this.downLatch.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			for (int i = 0; i < 20; i++) {
				System.out.println(Thread.currentThread().getName() + "====>" + i);
			}

			// if(name.equals("B"))
			this.downLatch.countDown();
		}

	}

	public static void test1() {
		ExecutorService service = Executors.newFixedThreadPool(2);
		Test4 tt = new Test4();
		CountDownLatch downLatch = new CountDownLatch(1);
		service.execute(tt.new DTask(downLatch, "A"));
		service.execute(tt.new DTask(downLatch, "B"));
		service.shutdown();

	}

	public static void main(String[] args) {
		test1();

	}

}

 

3.join方法

将线程B加入到线程A的尾部,当A执行完后B才执行。示例如下。

 

package com.thread_lc;

public class Th extends Thread {
	private final String name;

	public Th(String name) {
		this.name = name;
	}

	@Override
	public void run() {
		super.run();
		for (int i = 0; i < 100; i++)
			System.err.println(name + "\t" + i);
	}

	public static void main(String[] args) throws Exception {
		Th t = new Th("t1");
		Th t2 = new Th("t2");
		t.start();
		t.join();
		t2.start();
	}
}

 

 

 

 

 

  • 4
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值