最近在网上看到一些线程成的面试题,正好之前没有看到过,就自己私下实现了下,有备无患
1、用3个线程循环控制打印ABC,连续10次
public class Test {
public static void main(String[] args) {
MajusculeABC maj = new MajusculeABC();
Thread t_a = new Thread(new Thread_ABC(maj, 'A'));
Thread t_b = new Thread(new Thread_ABC(maj, 'B'));
Thread t_c = new Thread(new Thread_ABC(maj, 'C'));
t_a.start();
t_b.start();
t_c.start();
}
}
/**
* 通过 MajusculeABC对象来控制循环次数,因为在线程做了条件处理,所以每个数字都只有一个线程能执行打印
*/
class MajusculeABC {
private final static AtomicInteger sum = new AtomicInteger(30);
public int getSum() {
return sum.get();
}
public void deSum() {
sum.decrementAndGet();
}
}
class Thread_ABC implements Runnable {
private MajusculeABC maj;
private char name;
Thread_ABC(MajusculeABC maj, char name) {
this.maj = maj;
this.name = name;
}
@Override
public void run() {
int sum = maj.getSum();
while (sum > 0) {
if (name == 'A' && sum % 3 == 0) {
System.out.print(name);
maj.deSum();
}
if (name == 'B' && sum % 3 == 2) {
System.out.print(name);
maj.deSum();
}
if (name == 'C' && sum % 3 == 1) {
System.out.print(name);
maj.deSum();
}
sum = maj.getSum();
}
System.out.println();
}
}
2、实现死锁
public class DeadLock {
private static final String a = "A";
private static final String b = "B";
public static void main(String[] args) {
new DeadLock().deadLock();
}
/**
* 实现死锁的思路,需要同时持有2把或者多把锁才能执行任务
* 2个线程竞争,每个线程都只能拿到一把锁,都需要等待另外的线程去持有锁
*/
public void deadLock() {
Thread thread1 = new Thread(()->{
synchronized (a){
System.out.println(Thread.currentThread().getName()+" get a lock");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (b){
System.out.println(Thread.currentThread().getName()+" get b lock");
System.out.println(b);
}
}
},"thread1");
Thread thread2 = new Thread(()->{
synchronized (b){
System.out.println(Thread.currentThread().getName()+" get b lock");
synchronized (a){
System.out.println(Thread.currentThread().getName()+" get a lock");
System.out.println(a);
}
}
},"thread2");
thread1.start();
thread2.start();
}
}