其他
两个线程如何交替执行,一个输出偶数一个输出奇数?
synchronized实现
class ThreadPrintDemo2 {
public static void main(String[] args) {
final ThreadPrintDemo2 demo2 = new ThreadPrintDemo2();
Thread t1 = new Thread(demo2::print1);
Thread t2 = new Thread(demo2::print2);
t1.start();
t2.start();
}
public synchronized void print2() {
for (int i = 1; i <= 100; i += 2) {
System.out.println(i);
this.notify();
try {
this.wait();
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
public synchronized void print1() {
for (int i = 0; i <= 100; i += 2) {
System.out.println(i);
this.notify();
try {
this.wait();
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
}
CAS 实现
public class ThreadPrintDemo {
static AtomicInteger cxsNum = new AtomicInteger(0);
static volatile boolean flag = false;
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (; 100 > cxsNum.get(); ) {
if (!flag && (cxsNum.get() == 0 || cxsNum.incrementAndGet() % 2 == 0)) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
System.out.println(cxsNum.get());
flag = true;
}
}
}
);
Thread t2 = new Thread(() -> {
for (; 100 > cxsNum.get(); ) {
if (flag && (cxsNum.incrementAndGet() % 2 != 0)) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
System.out.println(cxsNum.get());
flag = false;
}
}
}
);
t1.start();
t2.start();
}
}
volatile实现
class ThreadPrintDemo3{
static volatile int num = 0;
static volatile boolean flag = false;
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (; 100 > num; ) {
if (!flag && (num == 0 || ++num % 2 == 0)) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
System.out.println(num);
flag = true;
}
}
}
);
Thread t2 = new Thread(() -> {
for (; 100 > num; ) {
if (flag && (++num % 2 != 0)) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
System.out.println(num);
flag = false;
}
}
}
);
t1.start();
t2.start();
}
}
我们使用 volatile 变量代替 CAS 变量,减轻使用 CAS 的消耗,注意,这里 ++num 不是原子的,但不妨碍,因为有 flag 变量控制。而 num 必须是 volatile 的,如果不是,会导致可见性问题。
彩蛋:如何翻转字符串?
class ReverseDemo {
public static void main(String[] args) {
String test = "abcdefg";
System.out.println(new StringBuilder(test).reverse());
char[] arr = test.toCharArray();
for (int i = arr.length - 1; i >= 0; i--) {
System.out.print(arr[i]);
}
}
}
作者:莫那·鲁道
来源:cnblogs.com/stateis0/p/9091254.html
- END -
点击「阅读原文」和栈长学更多~