package t3.copy; public class ThreadA extends Thread { private Object lock; public ThreadA(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
try {
while(true) {
synchronized (lock) {
if(Run.flag) {
System.out.println(Thread.currentThread().getName() + " ~~~~ ");
Run.flag = !Run.flag;
lock.wait();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} }
package t3.copy; public class ThreadB extends Thread { private Object lock; public ThreadB(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
try {
while(true) {
synchronized (lock) {
if(!Run.flag) {
System.out.println(Thread.currentThread().getName() + " !!!! ");
Run.flag = !Run.flag;
lock.notify();
}
} }
} catch (Exception e) {
e.printStackTrace();
}
} }
package t3.copy; public class Run { public static boolean flag = true; public static void main(String[] args) {
try {
Object lock = new Object();
ThreadA a = new ThreadA(lock);
a.start();
Thread.sleep(50);
ThreadB b = new ThreadB(lock);
b.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
不知道可不可以不借助于中间变量判断。
不借助于中间变量判断,但是交替打印次数一致。
package conditionTest.copy; import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock; public class MyService { private ReentrantLock lock = new ReentrantLock();
private Condition conditionSet = lock.newCondition();
private Condition conditionGet = lock.newCondition(); public void set() {
try {
lock.lock();
// while(hasValue) {
// }
System.out.println("打印★★★★★★");
conditionGet.signal();
conditionSet.await();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
lock.unlock();
}
} public void get() {
try {
lock.lock();
System.out.println("打印☆☆☆☆☆☆");
conditionSet.signal();
conditionGet.await();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
lock.unlock();
}
} }
package conditionTest.copy; public class MyThreadA extends Thread { private MyService service; public MyThreadA(MyService service) {
super();
this.service = service;
} @Override
public void run() {
for(int i=0; i<100; i++) {
service.set();
}
} }
package conditionTest.copy; public class MyThreadB extends Thread { private MyService service; public MyThreadB(MyService service) {
super();
this.service = service;
} @Override
public void run() {
for(int i=0; i<100; i++) {
service.get();
}
} }
package conditionTest.copy; public class Run { public static void main(String[] args) {
MyService service = new MyService();
MyThreadA a = new MyThreadA(service);
a.start();
MyThreadB b = new MyThreadB(service);
b.start();
} }