Java交替打印两个字符串
一、使用volatile关键字
public class Main {
volatile int x = 0;
Main() {
new Thread(() -> {
while (x < 100) {
while (x % 2 == 0) ;
System.out.print("A");
x++;
}
}).start();
new Thread(() -> {
while (x < 100) {
while (x % 2 == 1) ;
System.out.print("B");
x++;
}
}).start();
}public static void main(String[] args) {
new Main();
}
}
二、使用atomicInteger
import java.util.concurrent.atomic.AtomicInteger;
public class Main {Main() {
final AtomicInteger x = new AtomicInteger(0);
new Thread(() -> {
while (x.get() < 100) {
while (x.get() % 2 == 0) ;
System.out.print("A");
x.incrementAndGet();
}
}).start();
new Thread(() -> {
while (x.get() < 100) {
while (x.get() % 2 == 1) ;
System.out.print("B");
x.incrementAndGet();
}
}).start();
}public static void main(String[] args) {
new Main();
}
}
三、使用锁
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
Lock x = new ReentrantLock();
int index = 0;
Main() {
new Thread(() -> {
boolean over = false;
while (!over) {
if (index % 2 == 0) {
x.lock();
if (index % 2 == 0) {
System.out.print("A");
index++;
}
over = index > 100;
x.unlock();
}
}
}).start();
new Thread(() -> {
boolean over = false;
while (!over) {
if (index % 2 == 1) {
x.lock();
if (index % 2 == 1) {
System.out.print("B");
index++;
}
over = index > 100;
x.unlock();
}
}
}).start();
}public static void main(String[] args) {
new Main();
}
}
四、使用synchronized关键字
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
int index = 0;
Main() {
new Thread(() -> {
boolean over = false;
while (!over) {
if (index % 2 == 0) {
synchronized (this) {
if (index % 2 == 0) {
System.out.print("A");
index++;
}
over = index > 100;
}
}
}
}).start();
new Thread(() -> {
boolean over = false;
while (!over) {
if (index % 2 == 1) {
synchronized (this) {
if (index % 2 == 1) {
System.out.print("B");
index++;
}
over = index > 100;
}
}
}
}).start();
}public static void main(String[] args) {
new Main();
}
}
五、使用Python 【Java交替打印两个字符串】JavaScript是单线程的,Python可以实现多线程,但是Python的多线程不能充分利用多核。
这就相当于Python天生就不需要volatile。
a = "床前明月光疑是地上霜"
from threading import Threadindex = 0def one():
global index
while index < len(a):
while index % 2 == 0:
pass
if index >= len(a): break
print(a[index])
index += 1def two():
global index
while index < len(a):
while index % 2 == 1:
pass
if index >= len(a): break
print(a[index])
index += 1Thread(target=one).start()
Thread(target=two).start()
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 事件代理
- Java|Java OpenCV图像处理之SIFT角点检测详解
- java中如何实现重建二叉树
- 数组常用方法一
- 【Hadoop踩雷】Mac下安装Hadoop3以及Java版本问题
- Java|Java基础——数组
- RxJava|RxJava 在Android项目中的使用(一)
- java之static、static|java之static、static final、final的区别与应用
- Java基础-高级特性-枚举实现状态机