以前一直对多线程这一块很模糊,平时工作中也很少用到(技术太渣),闲来无事就写了一下面试经常会让手写的循环打印。
两个线程中传入了同一个对象,所以如果一个线程加锁之后,另一个线程就不可以访问该对象所拥有的所有同步方法,就是用这种思想,实现了下面的循环打印。
1、用Lock实现
package com.cn;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest {
Lock lock = new ReentrantLock();
Condition c1 = lock.newCondition();
int status = 1;
public static void main(String[] args) {
LockTest lockTest = new LockTest();
Run1 r1 = new Run1(lockTest);
Run2 r2 = new Run2(lockTest);
new Thread(r1).start();
new Thread(r2).start();
}
static class Run1 implements Runnable{
private LockTest lockTest;
public Run1(LockTest lockTest) {
this.lockTest = lockTest;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
lockTest.printA();
}
}
}
static class Run2 implements Runnable{
private LockTest lockTest;
public Run2(LockTest lockTest) {
this.lockTest = lockTest;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
lockTest.printB();
}
}
}
public void printA() {
try {
lock.lock();
while (status != 1) {
try {
c1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A");
status = 2;
c1.signal();
} finally {
lock.unlock();
}
}
public void printB() {
try {
lock.lock();
while (status != 2) {
try {
c1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B");
status = 1;
c1.signal();
} finally {
lock.unlock();
}
}
}
2、用synchronized实现
package com.cn;
public class ThreadTest {
private int status = 1;
public static void main(String[] args) {
ThreadTest t = new ThreadTest();
ThreadOne t1 = new ThreadOne(t);
ThreadTwo t2 = new ThreadTwo(t);
new Thread(t1, "thread1").start();
new Thread(t2, "thread2").start();
}
static class ThreadOne implements Runnable{
private ThreadTest threadTest;
public ThreadOne(ThreadTest threadTest) {
this.threadTest = threadTest;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
threadTest.printA();
}
}
}
static class ThreadTwo implements Runnable{
private ThreadTest threadTest;
public ThreadTwo(ThreadTest threadTest) {
this.threadTest = threadTest;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
threadTest.printB();
}
}
}
public void printA(){
synchronized (this) {
while (status != 1) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A");
status = 2;
this.notifyAll();
}
}
public void printB(){
synchronized (this) {
while (status != 2) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B");
status = 1;
this.notifyAll();
}
}
}
输出结果为: