美文网首页
Chapter 21 并发

Chapter 21 并发

作者: Dandelion637 | 来源:发表于2018-05-24 18:28 被阅读7次

    7

    将时间改为0
    原输出

    DaemonSpawn 0 started, d.isDaemon() = true, DaemonSpawn 1 started, DaemonSpawn 2 started, DaemonSpawn 3 started, DaemonSpawn 4 started, DaemonSpawn 5 started, DaemonSpawn 6 started, DaemonSpawn 7 started, DaemonSpawn 8 started, DaemonSpawn 9 started, t[0].isDaemon() = true, t[1].isDaemon() = true, t[2].isDaemon() = true, t[3].isDaemon() = true, t[4].isDaemon() = true, t[5].isDaemon() = true, t[6].isDaemon() = true, t[7].isDaemon() = true, t[8].isDaemon() = true, t[9].isDaemon() = true, 
    

    修改后的输出

    d.isDaemon() = true, DaemonSpawn 0 started, DaemonSpawn 1 started, DaemonSpawn 2 started, DaemonSpawn 3 started, DaemonSpawn 4 started, DaemonSpawn 5 started, DaemonSpawn 6 started, DaemonSpawn 7 started, DaemonSpawn 8 started, DaemonSpawn 9 started, t[0].isDaemon() = true, t[1].isDaemon() = true, t[2].isDaemon() = true, 
    

    说明后台线程再执行过程中就被终止

    8

    //: concurrency/SimpleThread.java
    package concurrency; /* Added by Eclipse.py */
    
    // Inheriting directly from the Thread class.
    
    public class SimpleThread extends Thread {
        private int countDown = 5;
        private static int threadCount = 0;
    
        public SimpleThread() {
            // Store the thread name:
            super(Integer.toString(++threadCount));
            this.setDaemon(true);
            start();
        }
    
        public String toString() {
            return "#" + getName() + "(" + countDown + "), ";
        }
    
        public void run() {
            while (true) {
                System.out.print(this);
                if (--countDown == 0)
                    return;
            }
        }
    
        public static void main(String[] args) {
    
            for (int i = 0; i < 5; i++)
                new SimpleThread();
        }
    } /*
         * Output: #1(5), #1(4), #1(3), #1(2), #1(1), #2(5), #2(4), #2(3), #2(2),
         * #2(1), #3(5), #3(4), #3(3), #3(2), #3(1), #4(5), #4(4), #4(3), #4(2),
         * #4(1), #5(5), #5(4), #5(3), #5(2), #5(1),
         */// :~
    
    
    //: concurrency/SimplePriorities.java
    package concurrency; /* Added by Eclipse.py */
    
    // Shows the use of thread priorities.
    
    import java.util.concurrent.*;
    
    import net.mindview.util.DaemonThreadFactory;
    
    public class SimplePriorities implements Runnable {
        private int countDown = 5;
        private volatile double d; // No optimization
        private int priority;
    
        public SimplePriorities(int priority) {
            this.priority = priority;
        }
    
        public String toString() {
            return Thread.currentThread() + ": " + countDown;
        }
    
        public void run() {
            System.out.println("Thread Start");
            Thread.currentThread().setPriority(priority);
            while (true) {
                // An expensive, interruptable operation:
                for (int i = 1; i < 100000; i++) {
                    d += (Math.PI + Math.E) / (double) i;
                    if (i % 1000 == 0)
                        Thread.yield();
                }
                System.out.println(this);
                if (--countDown == 0) {
                    System.out.println("Thread return");        //Thread 结束
                    return;
                }
            }
    
        }
    
        public static void main(String[] args) {
            ExecutorService exec = Executors.newCachedThreadPool(new DaemonThreadFactory());
            for (int i = 0; i < 5; i++)
                exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));
            exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));
            exec.shutdown();
            System.out.println("main return");
        }
    }
    

    9

    11

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    class Mod7Generator {
        private int a = 0;
        private int b = 0;
        private volatile boolean cancled = false; 
        
    //  错误的代码
        public int next() {
            a += 4;
            b += 3;
            return a+b;
        }
    
    //  正确的代码
    //  public synchronized int next() {
    //      a += 4;
    //      b += 3;
    //      return a+b;
    //  }
        
        public void cancle() {
            cancled = true;
        }
        
        public boolean isCancled() {
            return cancled;
        }
    }
    
    class EvenChecker implements Runnable {
        private Mod7Generator m7g;
        private int id;
        
        public EvenChecker(Mod7Generator m7g, int id) {
            this.id = id;
            this.m7g = m7g;
        }
        
        @Override
        public void run() {
            int a;
            while(!m7g.isCancled()) {
                a = m7g.next();
                if(a%7 != 0) {
                    System.out.println(a + " not even!");
                    m7g.cancle();
                    return;
                }
            }
        }
    }
    
    public class Main {
        
        public static void test(Mod7Generator m7g, int ct) {
            ExecutorService exec = Executors.newCachedThreadPool();
            for(int i=0; i<ct; i++) {
                exec.execute(new EvenChecker(m7g, i));
            }
            exec.shutdown();
        }
        public static void main(String[] args) {
            Mod7Generator m7g = new Mod7Generator();
            test(m7g, 10);
        }
    }
    

    输出:

    284 not even!
    277 not even!
    291 not even!
    

    14

    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.concurrent.TimeUnit;
    
    public class Main {
        
        static final int N = 5000; 
        static int id = 0;
        public static void main(String[] args) {
            Timer timer = new Timer();
            for(int i=0; i<N; i++) {
                timer.schedule(new TimerTask() {
                    
                    @Override
                    public void run() {
                        if(id == 0) System.gc();  //Garbage Collection
                        System.out.println("id= " + id++);
                    }
                }, 5000);
            }
    //      try {
    //          TimeUnit.MILLISECONDS.sleep(1000);
    //      } catch (InterruptedException e) {
    //          e.printStackTrace();
    //      }
    //      System.gc();
        }
    }
    

    发现如果不进行垃圾回收System.gc(),进程就不会停止,查阅了一下相关博客发现应该在线程里加上垃圾回收,但是每个都加上后发现运行速度明显降低,再次查阅博客发现只在其中一个GC即可参考链接

    相关文章

      网友评论

          本文标题:Chapter 21 并发

          本文链接:https://www.haomeiwen.com/subject/zpasjftx.html