49,919
社区成员




import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class test implements Runnable {
private static Object actors = new Object();
private static Object directors = new Object();
public int x;
private static Lock lock = new ReentrantLock();
public void run() {
System.out.println("进行转账");
if (x == 1) {
lock.lock();
synchronized (directors) {
System.out.println("演员开始转账");
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (actors) {
System.out.println("演员转账成功");
}
}
lock.unlock();
}
if (x == 0) {
lock.lock();
synchronized (actors) {
System.out.println("导演开始转账");
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (directors) {
System.out.println("导演转账成功");
}
}
lock.unlock();
}
}
public static void main(String[] args) {
test actor = new test();
test director = new test();
actor.x = 1;
director.x = 0;
new Thread(actor).start();
new Thread(director).start();
}
}
大概就是这意思,先看看这些方法怎么用吧。
public class test implements Runnable {
private static Object actors = new Object();
private static Object directors = new Object();
public int x;
public void run() {
System.out.println("进行转账");
if (x == 1) {
synchronized (directors) {
System.out.println("演员开始转账");
try {
Thread.sleep(500);
directors.wait();
actors.notify();
} catch (Exception e) {
e.printStackTrace();
}
synchronized (actors) {
System.out.println("演员转账成功");
}
}
}
if (x == 0) {
synchronized (actors) {
System.out.println("导演开始转账");
try {
Thread.sleep(500);
actors.wait();
directors.notify();
} catch (Exception e) {
e.printStackTrace();
}
synchronized (directors) {
System.out.println("导演转账成功");
}
}
}
}
public static void main(String[] args) {
test actor = new test();
test director = new test();
actor.x = 1;
director.x = 0;
new Thread(actor).start();
new Thread(director).start();
}
}
这是wait的