zoukankan      html  css  js  c++  java
  • [Java Concurrency] Chapter 1 Thread Management

    1. Creating and running a thread:

    (1) a class implements Runnable

    (2) override run()

    (3) start the thread by :
    (new Thread(new RunnableClass())).start();

    (4) the code:

    /**
     * Created by Min on 2/20/2017.
     */
    public class Calculator implements Runnable {
        private int number;
        public Calculator(int number) {
            this.number = number;
        }
    
        @Override
        public void run() {
            for (int i=1; i<=10; i++){
                System.out.printf("%s: %d * %d = %d
    ",Thread.
                        currentThread().getName(),number,i,i*number);
            }
        }
        public static void main(String[] args) {
            for (int i=1; i<=10; i++){
                Calculator calculator=new Calculator(i);
                Thread thread=new Thread(calculator);
                thread.start();
            }
        }
    }

    2. Getting and Setting Thread Information

    ID, Name, Priority and Status.

    Priority: 1~10, 1 is the minimum priority, 10 is the maximum priority

    status: new, runnable, blocked, waiting, time waiting, terminated

    code:

    System.out.println("Main : Status of Thread "+i+" : " +
                        threads[i].getState());
    这行代码当中原文应该是pw.println();
    但是我打印不出来,就用system.out代替了
    主要的函数是Thread.getState(), Thread.getId(), Thread.getName(), Thread.getPriority()
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    /**
     * Created by Min on 2/20/2017.
     */
    public class Calculator implements Runnable {
        private int number;
        public Calculator(int number) {
            this.number = number;
        }
    
        @Override
        public void run() {
            for (int i=1; i<=10; i++){
                System.out.printf("%s: %d * %d = %d
    ",Thread.
                        currentThread().getName(),number,i,i*number);
            }
        }
        private static void writeThreadInfo(PrintWriter pw, Thread
                thread, Thread.State state) {
            pw.printf("Main : Id %d - %s
    ",thread.getId(),thread.getName());
            pw.printf("Main : Priority: %d
    ",thread.getPriority());
            pw.printf("Main : Old State: %s
    ",state);
            pw.printf("Main : New State: %s
    ",thread.getState());
            pw.printf("Main : ************************************
    ");
        }
        public static void main(String[] args) {
            Thread threads[]=new Thread[10];
            Thread.State status[]=new Thread.State[10];
            for (int i=0; i<10; i++){
                threads[i]=new Thread(new Calculator(i));
                if ((i%2)==0){
                    threads[i].setPriority(Thread.MAX_PRIORITY);
                } else {
                    threads[i].setPriority(Thread.MIN_PRIORITY);
                }
                threads[i].setName("Thread "+i);
            }
            FileWriter file = null;
            try {
                file = new FileWriter(".\log.txt");
            } catch (IOException e) {
                e.printStackTrace();
            }
            PrintWriter pw = new PrintWriter(file);
            // log the status before the thread starts
            for (int i=0; i<10; i++){
                System.out.println("Main : Status of Thread "+i+" : " +
                        threads[i].getState());
                status[i]=threads[i].getState();
            }
            // start all threads
            for (int i=0; i<10; i++){
                threads[i].start();
            }
            // wait until all threads terminates
            boolean finish=false;
            while (!finish) {
                for (int i=0; i<10; i++){
                    if (threads[i].getState()!=status[i]) {
                        writeThreadInfo(pw, threads[i],status[i]);
                        status[i]=threads[i].getState();
                    }
                }
                finish=true;
                for (int i=0; i<10; i++){
                    finish=finish &&(threads[i].getState()== Thread.State.TERMINATED);
                }
            }
        }
    }

    3. Interrupting a thread

    A Java program with more than one execution thread only finishes when the execution of all of
    its threads end (more specifically, when all its non-daemon threads end its execution or when
    one of the threads use the System.exit() method).

    One peculiarity of this mechanism is that Thread has to check if it has been interrupted or
    not, and it can decide if it responds to the finalization request or not. Thread can ignore it
    and continue with its execution.

    一般情况下,所有线程结束之后或者一个程序调用了System.exit()之后才会结束,但是java提供了finish某一个线程的方法。

    一种方式是线程会定期检查有没有要finish它,线程可以决定它是否愿意被finish

    /**
     * Created by Min on 2/20/2017.
     */
    public class PrimeGenerator extends Thread {
        private boolean isPrime(long number) {
            if (number <=2) {
                return true;
            }
            for (long i=2; i<number; i++){
                if ((number % i)==0) {
                    return false;
                }
            }
            return true;
        }
        @Override
        public void run() {
            long number = 1L;
            while (true) {
                if (isPrime(number)) {
                    System.out.printf("Number %d is Prime", number);
                }
                if (isInterrupted()) {
                    System.out.printf("The prime Generator has been Interrupted");
                    return;
                }
                number++;
            }
        }
        public static void main(String[] args) {
            Thread task = new PrimeGenerator();
            task.start();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            task.interrupt();
        }
    }

    问题1:

    Thread的六个state分别有什么差别?

    问题2:

    Thread 和 Runnable 这两个Interface 有什么差别?

    问题3:

  • 相关阅读:
    JSON——JavaScript 对象表示法(JavaScript Object Notation)。
    jquery—— jQuery 是目前最流行的 JS 框架
    Bootstrap的css
    markdown编辑器与富文本编辑器优缺点比较--转载好文
    MATLAB绘图设置--中坐标显示间隔以及范围设置
    MATLAB绘图中参数导数的标注方法
    MATLAB 读取和写出Excel文件的方法-单个以及自动循环读写多个情况
    matlab 求和
    MATLAB画图中设置Marker过于密集怎么办-解决方法
    MPC特点原理以及各项参数的选择--引用别人的博客网址
  • 原文地址:https://www.cnblogs.com/Gryffin/p/6423418.html
Copyright © 2011-2022 走看看