问题:使用两个线程从0到1交替打印奇数和偶数
方法一:
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static volatile boolean flag = false;
public static AtomicInteger i=new AtomicInteger(1);
public static void main(String[] args) throws InterruptedException {
// 线程 A
new Thread(()->{
while (i.get()<=100)
{
if(!flag)
{
System.out.println(Thread.currentThread().getName() + " " + i.getAndIncrement());
flag=true;
}
}
},"线程A").start();
Thread.sleep(1000);
// 线程 B
new Thread(()->{
while (i.get()<=100)
{
if(flag)
{
System.out.println(Thread.currentThread().getName()+ " " + i.getAndIncrement());
flag=false;
}
}
},"线程B").start();
Thread.sleep(1000);
}
}
方法二:
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static AtomicInteger i=new AtomicInteger(1);
public static void main(String[] args) throws InterruptedException {
Object a = new Object();
Object b = new Object();
new Thread(new MyThread("A", b, a)).start();
Thread.sleep(1000);
new Thread(new MyThread("B", a, b)).start();
}
static class MyThread implements Runnable {
private String name;
private Object pre;
private Object self;
public MyThread(String name, Object pre, Object self) {
this.name = name;
this.pre = pre;
this.self = self;
}
@Override
public void run() {
while(i.get()<=100)
{
synchronized (pre)
{
synchronized (self)
{
System.out.println("线程"+name+":"+i.getAndIncrement());
self.notifyAll();
}
try {
if(i.get()==101)
{
pre.notifyAll();
}
else{
pre.wait();
}
}catch (Exception e)
{
throw new RuntimeException();
}
}
}
}
}
}