两个线程交替打印奇偶数
public class TwoThreadLock {
static Locklock =new ReentrantLock();
private int start =1;
private boolean flag;
public static void main(String[] args) {
TwoThreadLock twoThreadWaitNotifyLock =new TwoThreadLock();
Thread thread =new Thread(new OuNum(twoThreadWaitNotifyLock));
thread.setName("t1");
Thread thread1 =new Thread(new JiNum(twoThreadWaitNotifyLock));
thread1.setName("t2");
thread.start();
thread1.start();
}
public static class OuNumimplements Runnable {
TwoThreadLocknumber;
public OuNum(TwoThreadLock n1) {
this.number = n1;
}
@Override
public void run() {
while (number.start <=100) {
if (number.flag) {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() +":" +number.start);
number.start++;
number.flag =false;
}finally {
lock.unlock();
}
}
}
}
}
public static class JiNumimplements Runnable {
TwoThreadLocknumber;
public JiNum(TwoThreadLock n2) {
this.number = n2;
}
@Override
public void run() {
while (number.start <=100) {
if (!number.flag) {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() +":" +number.start);
number.start++;
number.flag =true;
}finally {
lock.unlock();
}
}
}
}
}