首页 > 编程语言 >Java: Thread

Java: Thread

时间:2023-12-16 17:01:16浏览次数:27  
标签:status Java pw Thread threads printf java

 

/**
 * encoding: utf-8
 * 版权所有 2023 涂聚文有限公司
 * 许可信息查看:
 * 描述:
 * # Author    : geovindu,Geovin Du 涂聚文.
 * # IDE       : IntelliJ IDEA 2023.1 Java 17
 * # Datetime  : 2023 - 2023/12/16 - 16:40
 * # User      : geovindu
 * # Product   : IntelliJ IDEA
 * # Project   : javademo
 * # File      : Calculator.java  类
 * # explain   : 学习
 **/

package Concurrency;

import java.lang.*;
import java.util.*;


/**
 * This class prints the multiplication table of a number
 *Concurrency
 * https://github.com/PacktPublishing/Java-9-Concurrency-Cookbook-Second-Edition
 * Java 9 Concurency Cookbook  by Javier Fernandez Gonzalez
 */
public class Calculator implements Runnable {

    /**
     * Method that do the calculations
     */
    @Override
    public void run() {
        long current = 1L;
        long max = 20000L;
        long numPrimes = 0L;

        System.out.printf("Thread '%s': START\n", Thread.currentThread().getName());
        while (current <= max) {
            if (isPrime(current)) {
                numPrimes++;
            }
            current++;
        }
        System.out.printf("Thread '%s': END. Number of Primes: %d\n", Thread.currentThread().getName(), numPrimes);
    }

    /**
     * Method that calculate if a number is prime or not
     *
     * @param number
     *            : The number
     * @return A boolean value. True if the number is prime, false if not.
     */
    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;
    }

}

  

/**
 * encoding: utf-8
 * 版权所有 2023 涂聚文有限公司
 * 许可信息查看:
 * 描述:
 * # Author    : geovindu,Geovin Du 涂聚文.
 * # IDE       : IntelliJ IDEA 2023.1 Java 17
 * # Datetime  : 2023 - 2023/12/16 - 16:41
 * # User      : geovindu
 * # Product   : IntelliJ IDEA
 * # Project   : javademo
 * # File      : CalculatorBLL.java  类
 * # explain   : 学习
 **/

package BLL;


import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.State;
import Concurrency.Calculator;

public class CalculatorBLL {


    /**
     * 线程 Concurrency 并行编程
     * https://github.com/PacktPublishing/Java-9-Concurrency-Cookbook-Second-Edition
     */
    public  static void CalculatorExample()
    {
        // Thread priority infomation
        System.out.printf("Minimum Priority: %s\n", Thread.MIN_PRIORITY);
        System.out.printf("Normal Priority: %s\n", Thread.NORM_PRIORITY);
        System.out.printf("Maximun Priority: %s\n", Thread.MAX_PRIORITY);

        Thread threads[];
        Thread.State status[];

        // Launch 10 threads to do the operation, 5 with the max
        // priority, 5 with the min
        threads = new Thread[10];
        status = new Thread.State[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(new Calculator());
            if ((i % 2) == 0) {
                threads[i].setPriority(Thread.MAX_PRIORITY);
            } else {
                threads[i].setPriority(Thread.MIN_PRIORITY);
            }
            threads[i].setName("My Thread " + i);
        }

        // Wait for the finalization of the threads. Meanwhile,
        // write the status of those threads in a file
        try (FileWriter file = new FileWriter("src\\data\\log.txt"); PrintWriter pw = new PrintWriter(file);) {

            // Write the status of the threads
            for (int i = 0; i < 10; i++) {
                pw.println("Main : Status of Thread " + i + " : " + threads[i].getState());
                status[i] = threads[i].getState();
            }

            // Start the ten threads
            for (int i = 0; i < 10; i++) {
                threads[i].start();
            }

            // Wait for the finalization of the threads. We save the status of
            // the threads and only write the status if it changes.
            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() == State.TERMINATED);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * This method writes the state of a thread in a file
     *
     * @param pw
     *            : PrintWriter to write the data
     * @param thread
     *            : Thread whose information will be written
     * @param state
     *            : Old state of the thread
     */
    private static void writeThreadInfo(PrintWriter pw, Thread thread, State state) {
        pw.printf("Main : Id %d - %s\n", thread.getId(), thread.getName());
        pw.printf("Main : Priority: %d\n", thread.getPriority());
        pw.printf("Main : Old State: %s\n", state);
        pw.printf("Main : New State: %s\n", thread.getState());
        pw.printf("Main : ************************************\n");
    }


}

  

调用:

import BLL.CalculatorBLL;

public class Main {

    /**
     *
     * @param args
     */
    public static void main(String[] args)
    {


        System.out.println("Hello java language world! 涂聚文!");

        CalculatorBLL cbll=new CalculatorBLL();
        cbll.CalculatorExample();


}

 

输出:

 

  

 

标签:status,Java,pw,Thread,threads,printf,java
From: https://www.cnblogs.com/geovindu/p/17905026.html

相关文章

  • Failed to convert property value of type 'java.lang.String' to required type 'ja
    后端springboot项目使用getMapper接受,字段写了转换注解@JsonFormat(shape=JsonFormat.Shape.STRING,pattern="yyyy-MM-ddHH:mm:ss",timezone="GMT+8")还报错Failedtoconvertpropertyvalueoftype'java.lang.String'torequiredtype'java......
  • Java 中变量的线程安全问题
    Java中的变量主要分为静态变量、普通成员变量、局部变量等,这些变量在单线程环境下是不会有线程安全问题的,但是多线程环境下实际情况又是什么样子的呢?1、成员变量和静态变量如果成员变量和静态变量不存在多个线程共享操作,那么不会有线程安全问题如果成员变量和静态变量被......
  • 无涯教程-Java - String intern()函数
    对于任何两个字符串s和t,当且仅当s.equals(t)为s时,s.intern()==t.intern()才为true。Stringintern()-语法这是此方法的语法-publicStringintern()Stringintern()-返回值此方法返回字符串对象的规范表示形式。Stringintern()-示例importjava.io.*;publicc......
  • 你知道哪几种Java锁?分别有什么特点?
    今天我们聊一聊Java锁的分类锁的7大分类需要首先指出的是,这些多种多样的分类,是评价一个事物的多种标准,比如评价一个城市,标准有人口多少、经济发达与否、城市面积大小等。而一个城市可能同时占据多个标准,以北京而言,人口多,经济发达,同时城市面积还很大。同理,对于Java中的锁而言......
  • 无涯教程-Java - int indexOf(String str)函数
    此方法返回指定子字符串首次出现在该字符串中的索引。如果不存在,则返回-1。intindexOf(Stringstr)-语法intindexOf(Stringstr)这是参数的详细信息-str   - 一个字符串。intindexOf(Stringstr)-示例importjava.io.*;publicclassTest{publicsta......
  • JavaScript: WebGL3D
    fragment.bns 文件用NotePad打开 WebGL3D用tomcat浏览#version300esprecisionmediumpfloat;uniformfloatuR;invec3vPosition;//接收从顶点着色器过来的顶点位置invec4finalLight;//接受顶点着色器传过来的最终光照强度outvec4fragColor;voidmain(){......
  • 将开源免费进行到底,ThreadX开源电脑端GUIBuilder图形开发工具GUIX Studio
    上个月微软刚刚宣布将ThreadXRTOS全家桶贡献给Eclipse基金会,免费供大家商用,宽松的MIT授权方式,就差这个GUIXStudio没有开源了,而且Windows还经常检索不到,并且也不提供离线包。1、软件包有点大,700MB,直接分享到百度云了:链接:https://pan.baidu.com/s/1tS8IDWrIXGiCTbHxwxEkDA  提......
  • Java基础语法
    一.注释  java中的注释有三种:       1.单行注释    //         2.多行注释    /**/         3.文档注释    /***/二.标识符  1.所有的标识符都应该以字母(A~Z a~z),美元符($),下划线(_)开头   2.首字符之后可以是字母(A......
  • MySQL锁:Java开发者必须掌握的关键技术
    一、介绍在多用户并发访问数据库时,为了保证数据的一致性和完整性,数据库系统需要使用锁来控制对共享资源的访问。MySQL作为一款流行的关系型数据库管理系统,也提供了丰富的锁机制来支持并发控制。对于Java开发者来说,了解和掌握MySQL锁是至关重要的,因为它可以帮助我们更好地设计和优化......
  • 无涯教程-Java - int indexOf(int ch, int fromIndex)函数
    此方法返回指定字符首次出现在该字符串中的索引,如果没有出现该字符,则从指定索引fromIndex或-1开始搜索。intindexOf-语法publicinindexOf(charch,intfromIndex)这是参数的详细信息-ch        - 一个字符。fromIndex  - 从中开始搜索的索......