多线程交替打印1-100
- 使用ReentrantLock锁
- 使用synchronized关键字
- 使用条件锁
使用ReentrantLock锁
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class ThreadExample extends Thread {private int id;private static int counter = 1;private static Lock lock = new ReentrantLock();public ThreadExample(int id) {this.id = id;}@Overridepublic void run() {while (counter < 100) {lock.lock();if (counter % 2 == id % 2) {System.out.println("thread " + id + ": " + counter);counter++;}lock.unlock();}}public static void main(String[] args) {Thread t1 = new ThreadExample(1);Thread t2 = new ThreadExample(2);t1.start();t2.start();}
}
使用synchronized关键字
public class ThreadExample extends Thread {private int id;private static int counter = 1;public ThreadExample(int id) {this.id = id;}@Overridepublic void run() {while (counter < 100) {synchronized (Thread.class) {if (counter % 2 == id % 2) {System.out.println("thread " + id + ": " + counter);counter++;}}}}public static void main(String[] args) {Thread t1 = new ThreadExample(1);Thread t2 = new ThreadExample(2);t1.start();t2.start();}
}
使用条件锁
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;public class UseCondition {private static int num = 1;private ReentrantLock lock = new ReentrantLock();private Condition conditionA = lock.newCondition();private Condition conditionB = lock.newCondition();void print1() throws InterruptedException {lock.lock();while (num < 100) {if (num % 2 == 0) {conditionA.await();}System.out.println(Thread.currentThread().getName() + " " + num++);conditionB.signal();}lock.unlock();}void print2() throws InterruptedException {lock.lock();while (num < 100) {if (num % 2 == 1) {conditionB.await();}System.out.println(Thread.currentThread().getName() + " " + num++);conditionA.signal();}lock.unlock();}
}
public class ThreadExample implements Runnable {private int id;private static UseCondition useCondition = new UseCondition() ;public ThreadExample(int id){this.id = id;}@Overridepublic void run() {if (id == 0){try {useCondition.print1();} catch (InterruptedException e) {throw new RuntimeException(e);}}else{try {useCondition.print2();} catch (InterruptedException e) {throw new RuntimeException(e);}}}public static void main(String[] args) {new Thread(new ThreadExample(0), "线程A").start();new Thread(new ThreadExample(1), "线程B").start();}
}