三个线程分别打印 A,B,C,打印 n 次,输出ABCABCABC....
public class Main {
private int times;
private int state; // 0: A 1: B 2: C
private final Lock lock = new ReentrantLock();
public void setTimes(int times) {
this.times = times;
}
public void print(String s, int tarState) {
for (int i = 0; i < times; ) {
lock.lock();
try {
if (state % 3 == tarState) {
state++;
i++;
System.out.print(s);
}
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
Main m = new Main();
m.setTimes(5);
new Thread(() -> {
m.print("A", 0);
}).start();
new Thread(() -> {
m.print("B", 1);
}).start();
new Thread(() -> {
m.print("C", 2);
}).start();
}
}
public class Main {
private int times;
private int state; // 0: A 1: B 2: C
private Object lock = new Object();
public void setTimes(int times) {
this.times = times;
}
public void print(String s, int tarState) {
for (int i = 0; i < times; i++) {
synchronized (lock) {
while (state % 3 != tarState) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(s);
state++;
lock.notifyAll();
}
}
}
public static void main(String[] args) {
Main m = new Main();
m.setTimes(5);
new Thread(() -> {
m.print("A", 0);
}).start();
new Thread(() -> {
m.print("B", 1);
}).start();
new Thread(() -> {
m.print("C", 2);
}).start();
}
}
public class Main {
private int times = 10;
private int state; // 0: A 1: B 2: C
private static Lock lock = new ReentrantLock();
private static Condition c1 = lock.newCondition(), c2 = lock.newCondition(), c3 = lock.newCondition();
public static void main(String[] args) {
Main m = new Main();
new Thread(() -> {
m.print("A", 0, c1, c2);
}, "A").start();
new Thread(() -> {
m.print("B", 1, c2, c3);
}, "B").start();
new Thread(() -> {
m.print("C", 2, c3, c1);
}, "C").start();
}
public void print(String s, int targetState, Condition current, Condition next) {
for (int i = 0; i < times; ) {
lock.lock();
try {
while (state % 3 != targetState) current.await();
state++;
i++;
System.out.print(s);
next.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
两个线程,交替打印1-100
public class Main {
private int limit = 100;
private int num = 1;
private Object lock = new Object();
public void print() {
synchronized (lock) {
while (num <= limit) {
System.out.println(Thread.currentThread().getName() + "print:" + num++);
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notifyAll();
}
}
public static void main(String[] args) {
Main m = new Main();
new Thread(() -> { m.print(); }, "奇数").start();
new Thread(() -> { m.print(); }, "偶数").start();
}
}
public class Main {
private int limit = 100;
private int num = 1;
private Lock lock = new ReentrantLock();
public void print(int target) {
while (num <= limit) {
lock.lock();
try {
if (num <= limit && num % 2 == target) {
System.out.println(Thread.currentThread().getName() + "print:" + num++);
}
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
Main m = new Main();
new Thread(() -> {
m.print(1);
}, "奇数").start();
new Thread(() -> {
m.print(0);
}, "偶数").start();
}
}
三个线程交替打印1~99
public class Main {
private int limit = 99;
private int num = 1;
private final Lock lock = new ReentrantLock();
public void print(int tarState) {
while (num <= limit) {
lock.lock();
try {
if (num <= limit && num % 3 == tarState) {
System.out.println(Thread.currentThread().getName() + "print: " + num++);
}
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
Main m = new Main();
new Thread(() -> {
m.print(0);
}, "线程3").start();
new Thread(() -> {
m.print(1);
},"线程1").start();
new Thread(() -> {
m.print(2);
}, "线程2").start();
}
}
两个线程交替输出 1A2B3C4D…26Z
public class Main {
private char letter = 'A';
private Object lock = new Object();
public void print() {
synchronized (lock) {
for (int i = 0; i < 26; i++) {
if (Thread.currentThread().getName().equals("数字线程")) {
System.out.print((i + 1));
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else if (Thread.currentThread().getName().equals("字母线程")) {
System.out.print((char) (i + letter));
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
lock.notifyAll();
}
}
public static void main(String[] args) {
Main m = new Main();
new Thread(() -> {
m.print();
}, "数字线程").start();
new Thread(() -> {
m.print();
}, "字母线程").start();
}
}
public class Main {
private static Thread numThread, letterThread;
public static void main(String[] args) {
letterThread = new Thread(() -> {
for (int i = 0; i < 26; i++) {
System.out.print((char) ('A' + i));
LockSupport.unpark(numThread);
LockSupport.park();
}
}, "letterThread");
numThread = new Thread(() -> {
for (int i = 1; i <= 26; i++) {
System.out.print(i);
LockSupport.unpark(letterThread);
LockSupport.park();
}
}, "numThread");
numThread.start();
letterThread.start();
}
}
交替打印foo bar n次
public class Main {
private int times = 10;
private Object lock = new Object();
public static void main(String[] args) {
Main m = new Main();
new Thread(() -> {
m.print("foo");
}).start();
new Thread(() -> {
m.print("bar");
}).start();
}
public void print(String s) {
synchronized (lock) {
for (int i = 0; i < times; i++) {
System.out.print(s);
lock.notifyAll();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notifyAll();
}
}
}
实现生产消费的队列
import java.util.LinkedList;
import static java.lang.Thread.sleep;
public class MessConAndPro {
public static void main(String[] args) {
MessageQueue queue = new MessageQueue(2);
for (int i = 0; i < 3; i++) {
int id = i;
new Thread(() -> {
queue.put(new Message(id, "值" + id));
}, "生产者" + i).start();
}
new Thread(() -> {
while (true) {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message take = queue.take();
System.out.println(take);
}
}, "消费者").start();
}
}
class MessageQueue {
private LinkedList<Message> list = new LinkedList<>();
private int capcity;
public MessageQueue(int capcity) {
this.capcity = capcity;
}
public Message take() {
synchronized (list) {
while (list.isEmpty()) {
try {
System.out.println("队列为空");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Message message = list.removeFirst();
System.out.println("消费" + message);
list.notifyAll();
return message;
}
}
public void put(Message message) {
synchronized (list) {
while (list.size() == capcity) {
try {
System.out.println("队列已满");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.addLast(message);
System.out.println("生产" + message);
list.notifyAll();
}
}
}
final class Message {
private int id;
private Object value;
public Message(int id, Object value) {
this.id = id;
this.value = value;
}
public int getId() {
return id;
}
public Object getValue() {
return value;
}
@Override
public String toString() {
return "Message{" +
"id=" + id +
", value=" + value +
'}';
}
}
public class BlockingQueueDemo<E> {
int size;//阻塞队列最大容量
ReentrantLock lock = new ReentrantLock();
LinkedList<E> list = new LinkedList<>();//队列底层实现
Condition notFull = lock.newCondition();//队列满时的等待条件
Condition notEmpty = lock.newCondition();//队列空时的等待条件
public BlockingQueueDemo(int size) {
this.size = size;
}
public void enqueue(E e) throws InterruptedException {
lock.lock();
try {
while (list.size() == size)//队列已满,在notFull条件上等待
notFull.await();
list.add(e);//入队:加入链表末尾
System.out.println("入队:" + e);
notEmpty.signal(); //通知在notEmpty条件上等待的线程
} finally {
lock.unlock();
}
}
public E dequeue() throws InterruptedException {
E e;
lock.lock();
try {
while (list.size() == 0)//队列为空,在notEmpty条件上等待
notEmpty.await();
e = list.removeFirst();//出队:移除链表首元素
System.out.println("出队:" + e);
notFull.signal();//通知在notFull条件上等待的线程
return e;
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
BlockingQueueDemo<Integer> queue =
new BlockingQueueDemo<Integer>(2);
for (int i = 0; i < 10; i++) {
int e = i;
new Thread(() -> {
try {
queue.enqueue(e);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
}).start();
}
for (int i = 0; i < 10; i++) {
new Thread(() -> {
try {
Integer e = queue.dequeue();
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
}).start();
}
}
}