- 两个线程交替打印1212121212
这题使用了原子的一个状态类表示当前可执行的线程。
/**
* @Author: tjc
* @description
* @Date Created in 14:35 2021-03-03
* 两个线程交替打印1212121212
*/
public class Demo6 {
public static void main(String[] args) {
AtomicInteger i = new AtomicInteger(0);
new Thread(new Print1(i)).start();
new Thread(new Print2(i)).start();
}
}
class Print1 implements Runnable{
private AtomicInteger i;
public Print1(AtomicInteger i) {
this.i = i;
}
public void run() {
while(true) {
if(i.get() == 0) {
System.out.print("1");
i.compareAndSet(0, 1);
}
}
}
}
class Print2 implements Runnable{
private AtomicInteger i;
public Print2(AtomicInteger i) {
this.i = i;
}
public void run() {
while(true) {
if(i.get() == 1) {
System.out.print("2");
i.compareAndSet(1, 0);
}
}
}
}
- 通过 N 个线程顺序循环打印从 0 至 100
/**
* @Author: tjc
* @description
* @Date Created in 16:05 2021-03-03
* 通过 N 个线程顺序循环打印从 0 至 100
*/
public class Demo3 {
public static void main(String[] args) {
AtomicInteger curThread = new AtomicInteger(1);
AtomicInteger count = new AtomicInteger(0);
new Thread(new PrintTask(1, 5, curThread, count)).start();
new Thread(new PrintTask(2, 5, curThread, count)).start();
new Thread(new PrintTask(3, 5, curThread, count)).start();
new Thread(new PrintTask(4, 5, curThread, count)).start();
new Thread(new PrintTask(5, 5, curThread, count)).start();
}
}
class PrintTask implements Runnable {
private AtomicInteger count;
private int no;
private int maxNum;
private AtomicInteger curThread;
private boolean start = true;
public PrintTask(int no, int maxNum, AtomicInteger curThread, AtomicInteger count) {
this.no = no;
this.maxNum = maxNum;
this.count = count;
this.curThread = curThread;
}
public void turn() {
if (curThread.get() >= maxNum) {
curThread.set(1);
} else {
curThread.incrementAndGet();
}
}
public void run() {
while (start) {
synchronized (curThread) {
while (no != curThread.get()) {
try {
curThread.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
turn();
if (count.get() > 100) {
start = false;
curThread.notifyAll();
break;
}
System.out.println("thread" + no + ": " + count.get());
count.getAndIncrement();
curThread.notifyAll();
}
}
System.out.println("thread" + no + " end.");
}
}
网友评论