3. 练习

1 习题内容

启动两个线程第一个线程打印ABCD…Z,第二个线程从1打印到26,两个线程交替打印A1B2C3…Z26

1.1 LockSupport
import java.util.concurrent.locks.LockSupport;

public class LockSupportTest {
    static char[] charactor = "ABCDEF".toCharArray();
    static char[] number = "123456".toCharArray();
    static Thread t1, t2;

    public static void main(String[] args) {
        t1 = new Thread(() -> {
            for (char c : number) {
                System.out.print(c);
                LockSupport.unpark(t2);
                LockSupport.park();
            }
        });
        t1.start();
        t2 = new Thread(() -> {
            for (char c : charactor) {
                LockSupport.park();
                System.out.print(c);
                LockSupport.unpark(t1);
            }
        });
        t2.start();
    }
}

1.2 CAS
public class CASTest {
    static char[] charactor = "ABCDEF".toCharArray();
    static char[] number = "123456".toCharArray();
    static Thread t1, t2;
    volatile static boolean trueOrFalse = true;

    public static void main(String[] args) {
        t1 = new Thread(() -> {
            for (char c : number) {
                while (trueOrFalse != true) {
                }
                System.out.print(c);
                trueOrFalse = false;
            }
        });
        t1.start();
        t2 = new Thread(() -> {
            for (char c : charactor) {
                while (trueOrFalse != false) {
                }
                System.out.print(c);
                trueOrFalse = true;
            }
        });
        t2.start();
    }
}

1.3 BlockingQueue
package com.mashibing.juc;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class BlockingQueueTest {
    static char[] charactor = "ABCDEF".toCharArray();
    static char[] number = "123456".toCharArray();
    static Thread t1, t2;
    static BlockingQueue queue1 = new LinkedBlockingQueue();
    static BlockingQueue queue2 = new LinkedBlockingQueue();

    public static void main(String[] args) {
        t1 = new Thread(() -> {
            for (char c : number) {
                try {
                    queue1.put(c);
                    System.out.print(queue2.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2 = new Thread(() -> {
            for (char c : charactor) {
                try {
                    System.out.print(queue1.take());
                    queue2.put(c);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t2.start();
    }
}

1.4 AtomicInteger
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerTest {
    static char[] charactor = "ABCDEF".toCharArray();
    static char[] number = "123456".toCharArray();
    static Thread t1, t2;
    static AtomicInteger at = new AtomicInteger(0);

    public static void main(String[] args) {
        t1 = new Thread(() -> {
            for (char c : number) {
                while (at.get() != 0) {
                }
                System.out.print(c);
                at.getAndIncrement();
            }
        });
        t1.start();
        t2 = new Thread(() -> {
            for (char c : charactor) {
                while (at.get() != 1) {
                }
                System.out.print(c);
                at.getAndDecrement();
            }
        });
        t2.start();
    }
}

1.5 synchronized+wait+notify
public class SynchronizedWatiNotifyTest {
    static char[] charactor = "ABCDEF".toCharArray();
    static char[] number = "123456".toCharArray();
    static Thread t1, t2;
    static Object obj = new Object();

    public static void main(String[] args) {


        t1 = new Thread(() -> {
            for (char c : number) {
                synchronized (obj) {
                    System.out.print(c);
                    try {
                        obj.wait();
                        obj.notify();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        });
        t1.start();
        t2 = new Thread(() -> {
            for (char c : charactor) {
                synchronized (obj) {
                    System.out.print(c);
                    obj.notify();
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t2.start();
    }
}
1.5 lock+condition
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockConditionTest {
    static char[] charactor = "ABCDEF".toCharArray();
    static char[] number = "123456".toCharArray();
    static Thread t1, t2;
    static Lock lock = new ReentrantLock();
    static Condition cond1 = lock.newCondition();
    static Condition cond2 = lock.newCondition();

    public static void main(String[] args) {
        t1 = new Thread(() -> {
            lock.lock();
            for (char c : number) {
                System.out.print(c);
                try {
                    //可以让出锁,signal无法让出锁
                    cond1.await();
                    cond2.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            lock.unlock();
        });
        t1.start();
        t2 = new Thread(() -> {
            lock.lock();
            for (char c : charactor) {
                System.out.print(c);
                try {
                    cond1.signal();
                    cond2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            lock.unlock();
        });
        t2.start();
    }
}

1.6 TransferQueue
package com.mashibing.juc;

import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;

public class TransferQueueTest {
    static char[] charactor = "ABCDEF".toCharArray();
    static char[] number = "123456".toCharArray();
    static Thread t1, t2;
    static TransferQueue tq = new LinkedTransferQueue();

    public static void main(String[] args) {
        t1 = new Thread(() -> {
            for (char c : number) {
                try {
                    tq.transfer(c);
                    System.out.print(tq.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2 = new Thread(() -> {
            for (char c : charactor) {
                try {
                    System.out.print(tq.take());
                    tq.transfer(c);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t2.start();
    }
}

1.7 PipedStream
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipedStreamTest {
    static char[] charactor = "ABCDEF".toCharArray();
    static char[] number = "123456".toCharArray();
    static Thread t1, t2;
    //PipedStream相当于在两个线程间建立了一个管子,该接口提供了阻塞的read方法,即读不到东西就阻塞
    //这个例子中实际上就是利用read阻塞的特性,将其当做一把锁,但效率特别低
    static PipedInputStream p1 = new PipedInputStream();
    static PipedOutputStream p2 = new PipedOutputStream();
    static PipedInputStream pp1 = new PipedInputStream();
    static PipedOutputStream pp2 = new PipedOutputStream();

    public static void main(String[] args) throws IOException {
        //将第一个线程的input和第二个线程的output连接起来
        p1.connect(p2);
        pp1.connect(pp2);
        t1 = new Thread(() -> {
            for (char c : number) {
                try {
                    p2.write(c);
                    System.out.print((char) (pp1.read()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2 = new Thread(() -> {
            for (char c : charactor) {
                try {
                    System.out.print((char) (p1.read()));
                    pp2.write(c);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        t2.start();
    }
}

你可能感兴趣的:(多线程与高并发编程)