一、synchronized关键字实现
public class MyThread1 implements Runnable {
private static Object lock = new Object();
private static int count;
private int no;
public MyThread1(int no) {
this.no = no;
}
@Override
public void run() {
while (true) {
synchronized (lock) {
if (count > 100) {
break;
}
if (count % 3 == this.no) {
System.out.println(this.no + "--->" + count);
count++;
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notifyAll();
}
}
}
}
二、ReentrantLock实现
public class MyThread2 implements Runnable {
private static ReentrantLock lock = new ReentrantLock();
private static Condition condition = lock.newCondition();
private static int count;
private int no;
public MyThread2(int no) {
this.no = no;
}
@Override
public void run() {
while (true) {
lock.lock();
if (count > 100) {
break;
} else {
if (count % 3 == this.no) {
System.out.println(this.no + "-->" + count);
count++;
} else {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
condition.signalAll();
lock.unlock();
}
}
}
三、main函数
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new MyThread2(0));
Thread t2 = new Thread(new MyThread2(1));
Thread t3 = new Thread(new MyThread2(2));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
}
}
网友评论