加锁方式
static int number = 0;
static class Ji implements Runnable {
private String name;
public Ji(String name) {
this.name = name;
}
@Override
public void run() {
while (number <= 100) {
synchronized (WithoutWaitNotify.class) {
if ((number % 2) == 1) {
System.out.println(number + " " + name);
number++;
}
}
}
}
}
static class Ou implements Runnable {
private String name;
public Ou(String name) {
this.name = name;
}
@Override
public void run() {
while (number <= 100) {
synchronized (WithoutWaitNotify.class) {
if ((number % 2) == 0) {
System.out.println(number + " " + name);
number++;
}
}
}
}
}
无锁方式
static volatile int count;
public static void main(String[] args) {
new Thread(new Ji()).start();
new Thread(new Ou()).start();
}
static class Ji implements Runnable {
int ccount = 1;
@Override
public void run() {
while (true) {
if (count > 1000)
break;
if (count == ccount) {
System.out.println("Ji: " + count);
ccount = count + 2;
count++;
}
}
}
}
static class Ou implements Runnable {
int ccount = 0;
@Override
public void run() {
while (true) {
if (count > 1000) {
break;
}
if (count == ccount) {
System.out.println("Ou: " + count);
ccount = count + 2;
count++;
}
}
}
}
网友评论