在Java中,线程等待和并发编程可以通过使用synchronized关键字、wait()和notify()方法、Lock和Condition等来实现。
public class Example {
private static Object lock = new Object();
public void doSomething() {
synchronized(lock) {
// 执行需要同步的操作
}
}
}
public class Example {
private static Object lock = new Object();
public void doSomething() {
synchronized(lock) {
try {
lock.wait(); // 线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void notifyThread() {
synchronized(lock) {
lock.notify(); // 唤醒等待的线程
}
}
}
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Example {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public void doSomething() {
lock.lock();
try {
condition.await(); // 线程等待
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void notifyThread() {
lock.lock();
try {
condition.signal(); // 唤醒等待的线程
} finally {
lock.unlock();
}
}
}
通过以上方法,可以实现线程等待和并发编程的结合,确保线程之间的协同工作和数据同步。