题目:
两个线程循环交替打印1-100。
代码:
public class DoubleThreadPrintNumber {
public static int i = 1;
public static Object lock = new Object();
private static AtomicInteger num = new AtomicInteger(1);
public static void main(String[] args) throws InterruptedException {
System.out.println("请输入要执行的操作:");
System.out.println("1、使用syncchronized实现");
System.out.println("2、使用AtomicInteger实现");
//创建Scanner对象,接受从控制台输入
Scanner input=new Scanner(System.in);
//接受String类型
String str=input.next();
switch (str){
case "1":doSynchronized() ;break;
case "2":doAtomicInteger();
break;
default:doAtomicInteger();
}
}
/**
* synchronized 关键字实现
*/
private static void doSynchronized(){
int TOTAL = 100;
Thread thread1 = new Thread(() -> {
while (i <= TOTAL) {
synchronized (lock) {
if (i % 2 == 1) {
System.out.println("i=" + i++);
lock.notify();
System.out.println("奇数打印完毕,释放锁");
} else {
try {
System.out.println("奇数锁等待");
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread thread2 = new Thread(() -> {
while (i <= TOTAL) {
synchronized (lock) {
if (i % 2 == 0) {
System.out.println("i=" + i++);
lock.notify();
System.out.println("偶数打印完毕,释放锁");
} else {
try {
System.out.println("偶数锁等待");
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
thread1.start();
thread2.start();
}
/**
* AtomicInteger实现
*/
public static void doAtomicInteger() {
ReentrantLock reentrantLock = new ReentrantLock();
Condition condition = reentrantLock.newCondition();
new Thread(new Runnable() {
int i =1;
// 第一个线程
@Override public void run() {
for ( ;num.intValue()<=100;){
if (num.intValue()%3==0){
// reentrantLock.lock();
System.out.println(num.intValue());
num.addAndGet(1);
//reentrantLock.unlock();
}else {
}
}
}
}).start();
// 第二个线程
new Thread(new Runnable() {
@Override public void run() {
for (;num.intValue()<=100;){
if (num.intValue()%3==1){
System.out.println(num.intValue());
num.addAndGet(1);
// reentrantLock.unlock();
}else {
// reentrantLock.lock();
}
}
}
}).start();
// 第二个线程
new Thread(new Runnable() {
@Override public void run() {
for (;num.intValue()<=100;){
if (num.intValue()%3==2){
System.out.println(num.intValue());
num.addAndGet(1);
// reentrantLock.unlock();
}else {
// reentrantLock.lock();
}
}
}
}).start();
}
}