题目:使用多线程实现输出的效果为: 1 -1 2 -2 3 -3 4 -4 …
方法一:公平锁解决两个线程交替执行
package com.thread.synchronizedDemo.lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockDemo implements Runnable {
private int j = 1;
ReentrantLock lock = new ReentrantLock(true);
@Override
public void run() {
for(int i = 1; i < 100; i++){
lock.lock();
try{
System.out.println(Thread.currentThread().getName()+" "+i*j);
j=-j;
}finally{
lock.unlock();
}
}
}
}
package com.thread.synchronizedDemo.lock;
public class TestLock {
public static void main(String[] args) {
LockDemo lockDemo = new LockDemo();
new Thread(lockDemo,"线程1").start();
new Thread(lockDemo,"线程2").start();
}
}
结果为:
线程1 1
线程2 -1
线程1 2
线程2 -2
线程1 3
线程2 -3
线程1 4
线程2 -4
线程1 5
线程2 -5
线程1 6
线程2 -6
线程1 7
线程2 -7
线程1 8
线程2 -8
线程1 9
线程2 -9
线程1 10
线程2 -10
线程1 11
........
方法二:采用wait()和notify()方法解决两个线程交替执行
public class Demo11 {
public static void main(String[] args) {
final Object object = new Object();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i < 100; i++) {
synchronized (object) {
try {
System.out.println(Thread.currentThread().getName() + " " + i);
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}, "A").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i < 100; i++) {
synchronized (object) {
System.out.println(Thread.currentThread().getName() + " " + (-1) * i);
object.notify();
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "B").start();
}
}
结果为:
A 1
B -1
A 2
B -2
A 3
B -3
A 4
B -4
A 5
B -5
A 6
B -6
A 7
B -7
.......