多线程

1 ThreadLocal

public class TestM {
    public static void main(String[] args)  {
        for (int i = 0; i < 2; i++) {
            new Thread() {
                @Override
                public void run() {
                    MyThreadScopData m = MyThreadScopData.getThreadInstance();
                    m.setAge(new Random().nextInt());
                    m.setName(new Random().nextInt() + "");
                    new A().get();
                    new B().get();
                }
            }.start();
        }
    }
    static class A {
        void get() {
            MyThreadScopData instance = MyThreadScopData.getThreadInstance();
            System.out.println(Thread.currentThread().getName() + "a" + instance.getName());
            System.out.println(Thread.currentThread().getName() + "a" + instance.getAge());
        }
    }
    
    static class B {
        void get() {
            MyThreadScopData instance = MyThreadScopData.getThreadInstance();
            System.out.println(Thread.currentThread().getName() + "b" + instance.getName());
            System.out.println(Thread.currentThread().getName() + "b" + instance.getAge());
        }
    }
}

class MyThreadScopData{
    private static ThreadLocal<MyThreadScopData> map = new ThreadLocal<>();
    private MyThreadScopData() {}
    public static MyThreadScopData getThreadInstance() {
        MyThreadScopData instance = map.get();
        if (null == instance) {
            instance = new MyThreadScopData();
            map.set(instance);
        }
        return instance;
    }
    
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
}
View Code

2 多个线程共享对象,

public class TestM {
    public static void main(String[] args)  {
        final ShareData data = new ShareData();
        new Thread() {
            public void run() {
                data.increase();
            }
        }.start();
        
        new Thread() {
            public void run() {
                data.decrease();
            }
        }.start();
    }
}

class ShareData {
    private int i = 0;
    public synchronized void increase() {
        i++;
    }
    public synchronized void decrease() {
        i--;
    }
}
View Code

3 线程池

public class TestM {
    public static void main(String[] args)  {
        ExecutorService service = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            final int task = i;
            service.execute(new Runnable() {
                
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "  " + task); 
                }
            });
        }
        service.shutdown();
        
        Executors.newScheduledThreadPool(3).schedule(new Runnable() {
            
            @Override
            public void run() {
                // TODO Auto-generated method stub
                System.out.println("bomb");
            }
        }, 2, TimeUnit.SECONDS);
    }
View Code

4 返回值的线程池

public class TestM {
    public static void main(String[] args)  {
        ExecutorService service = Executors.newSingleThreadExecutor();
        Future<Integer> future = service.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                // TODO Auto-generated method stub
                return new Random().nextInt();
            }
        });
        try {
            System.out.println(future.get());
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ExecutorService executor = Executors.newFixedThreadPool(3);
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(executor);
        for (int i = 0; i < 10; i++) {
            final int t = i;
            completionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    Thread.sleep(new Random().nextInt(1000));
                    return t;
                }
            });
        }
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println(completionService.take().get().toString());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
View Code

5 读写锁

public class CacheDemo {
 
    private Map<String, Object> map = new HashMap<>();
    public static void main(String[] args) {
        
    }
    private ReadWriteLock lock = new ReentrantReadWriteLock();
    public Object getData(String key) {
        lock.readLock().lock();
        Object value = null;
        try {
            value = map.get(key);
            if (value == null) {
                lock.readLock().unlock();
                lock.writeLock().lock();
                try {
                    if (value == null) {
                        value = "  fd";
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                } finally {
                    lock.writeLock().unlock();
                }
                lock.readLock().lock();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }finally {
            lock.readLock().unlock();
        }
        return value;
    }
}
View Code

 6 Candition 用与线程间通信,协调, 3个线程间通信

class Three {
    private int i = 1;
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    public void print1() {
        lock.lock();
        try {
            while (i != 1) {
                condition1.await();
            }
            System.out.println("1");
            i = 2;
            condition2.signal();
        } catch (Exception e) {
            // TODO: handle exception
        }finally {
            lock.unlock();
        }
    }
    public void print2() {
        lock.lock();
        try {
            while (i != 2) {
                condition2.await();
            }
            System.out.println("2");
            i = 3;
            condition3.signal();
        } catch (Exception e) {
            // TODO: handle exception
        }finally {
            lock.unlock();
        }
    }
    public void print3() {
        lock.lock();
        try {
            while (i != 3) {
                condition3.await();
            }
            System.out.println("3");
            i = 1;
            condition1.signal();
        } catch (Exception e) {
            // TODO: handle exception
        }finally {
            lock.unlock();
        }
    }
}
View Code
 class BoundedBuffer {
   final Lock lock = new ReentrantLock();
   final Condition notFull  = lock.newCondition(); 
   final Condition notEmpty = lock.newCondition(); 

   final Object[] items = new Object[100];
   int putptr, takeptr, count;

   public void put(Object x) throws InterruptedException {
     lock.lock();
     try {
       while (count == items.length) 
         notFull.await();
       items[putptr] = x; 
       if (++putptr == items.length) putptr = 0;
       ++count;
       notEmpty.signal();
     } finally {
       lock.unlock();
     }
   }

   public Object take() throws InterruptedException {
     lock.lock();
     try {
       while (count == 0) 
         notEmpty.await();
       Object x = items[takeptr]; 
       if (++takeptr == items.length) takeptr = 0;
       --count;
       notFull.signal();
       return x;
     } finally {
       lock.unlock();
     }
   } 
 }
View Code

 7 semaphore信号灯,控制可以有几个线程同时运行。

public class CacheDemo {

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 10; i++) {
            Runnable runnable = new Runnable() {
                
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    try {
                        semaphore.acquire();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("thread " + Thread.currentThread().getName() + " join in hava"
                            + (3 - semaphore.availablePermits()) + " thread");
                    
                    try {
                        Thread.sleep(new Random().nextInt(10000));
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    
                    System.out.println("thread " + Thread.currentThread().getName() + " go away hava"
                            + (3 - semaphore.availablePermits()) + " thread");
                    semaphore.release();
                }
            };
            service.execute(runnable);
        }
    }
}
View Code

8 CyclicBarrier 多个线程相互等待,如旅游坐车等其他同学。

public class CacheDemo {

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        final CyclicBarrier barrier = new CyclicBarrier(3);
        for (int i = 0; i < 3; i++) {
            Runnable runnable = new Runnable() {
                
                @Override
                public void run() {
                    try {
                        Thread.sleep(new Random().nextInt(1000));
                        System.out.println(Thread.currentThread().getName() + "  到达  1"
                                + " has " + (barrier.getNumberWaiting() + 1));
                        barrier.await();
                        
                        Thread.sleep(new Random().nextInt(1000));
                        System.out.println(Thread.currentThread().getName() + "  到达  2"
                                + " has " + (barrier.getNumberWaiting() + 1));
                        barrier.await();
                        
                        Thread.sleep(new Random().nextInt(1000));
                        System.out.println(Thread.currentThread().getName() + "  到达  3"
                                + " has " + (barrier.getNumberWaiting() + 1));
                        barrier.await();
                        
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
            };
            service.execute(runnable);
        }
    }
}
View Code

9 CountDownLatch  多个人通知一个人, 运动员跑到终点,通知裁判宣布成绩

一个人通知多个人,裁判打枪,通知运动员跑

public class CacheDemo {

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        final CountDownLatch c1 = new CountDownLatch(1);
        final CountDownLatch c2 = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            Runnable runnable = new Runnable() {
                
                @Override
                public void run() {
                    try {
                        c1.await();
                        System.out.println(Thread.currentThread().getName() + " get order ");
                        Thread.sleep(new Random().nextInt(10000));
                        System.out.println(Thread.currentThread().getName() + "");
                        c2.countDown();
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
            };
            service.execute(runnable);
        }
        try {
            Thread.sleep(1000);
            System.out.println("put order");
            c1.countDown();
            System.out.println("wait get result");
            c2.await();
            System.out.println(" 得到了结果  ");
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}
View Code

10 Exchanger 线程间交换东西,如买毒和卖

public class CacheDemo {

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        final Exchanger<String> exchanger = new Exchanger<>();
            Runnable runnable1 = new Runnable() {
                
                @Override
                public void run() {
                    try {
                        String data1 = "111";
                        System.out.println(Thread.currentThread().getName() + " huan qu " + data1);
                        Thread.sleep(new Random().nextInt(10000));
                        String data2 = exchanger.exchange(data1);
                        System.out.println(Thread.currentThread().getName() + " get  " + data2);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
            };
            service.execute(runnable1);
            
Runnable runnable2 = new Runnable() {
                
                @Override
                public void run() {
                    try {
                        String data1 = "222";
                        System.out.println(Thread.currentThread().getName() + " huan qu " + data1);
                        Thread.sleep(new Random().nextInt(10000));
                        String data2 = exchanger.exchange(data1);
                        System.out.println(Thread.currentThread().getName() + " get  " + data2);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
            };
            service.execute(runnable2);
        }
    }
View Code

11

posted on 2017-11-19 00:11  wheleetcode  阅读(168)  评论(0编辑  收藏  举报