该问题大概有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();
}
}
版权声明:本文为hellorichen原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。