一、使用volatile关键字实现
public class Print10 {
static volatile int i = 0;
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
while(i < 20){
synchronized (Print10.class){
// 锁的是类锁,所以要释放类的锁
Print10.class.notify(); // 唤醒其他线程可以抢锁了
System.out.println(Thread.currentThread().getName() + "打印:"+ i++);
try {
Print10.class.wait(); // 让此线程等待,避免下次和其他线程抢锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Thread t1 = new Thread(runnable,"t1");
Thread t2 = new Thread(runnable,"t2");
t1.start();
t2.start();
}
}
public class Print10 {
static volatile int state = 0;
static volatile int i = 0;
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
while(i < 20){
if(state % 2 == 0 && Thread.currentThread().getName().equals("t1")){
System.out.println(Thread.currentThread().getName() + "打印:"+ i);
state++;
i++;
}
if (state % 2 == 1 && Thread.currentThread().getName().equals("t2")){
System.out.println(Thread.currentThread().getName() + "打印:"+ i);
state++;
i++;
}
}
}
};
Thread t1 = new Thread(runnable,"t1");
Thread t2 = new Thread(runnable,"t2");
t1.start();
t2.start();
}
}
二、使用原子类实现 AtomicInteger
public class Print100 {
static volatile AtomicInteger i = new AtomicInteger(0);
public static void main(String[] args) {
Thread t1 = new Thread(new print(i),"t1");
Thread t2 = new Thread(new print(i),"t2");
t1.start();
t2.start();
}
}
class print implements Runnable{
volatile static AtomicInteger i;
public print(AtomicInteger i) {
this.i = i;
}
@Override
public void run() {
while(i.get() < 10) {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + "打印了:" + i.incrementAndGet());
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}