常用类——System类

System类

概述

  • 代表当前 Java 程序的运行平台,系统级的很多属性和控制方法都放置在该类的内部。
  • 由于该类的构造方法是 private 的,所以无法创建该类的对象,也就是无法实例化该类。

类中的常用方法

方法名说明
public static void exit(int status)终止当前运行的Java虚拟机,非零表示异常终止
public static long currentTimeMillis()返回当前时间(以毫秒为单位)

代码示例

1. exit

public class ExitDemo {
    public static void main(String[] args) {
        System.out.println("开始");
        //终止当前运行的Java虚拟机,非零表示异常终止
        System.exit(0);
        System.out.println("结束");
    }
}

2. currentTimeMillis

(1)方法使用
System.currentTimeMillis()
(2)判断程序运行耗时
public class CurrentTimeMillisDemo {
    public static void main(String[] args) {
        //返回当前时间(以毫秒为单位)  1000ms = 1s
        System.out.println(System.currentTimeMillis());//1970年1月1日 -- 至今
        //判断程序运行耗时
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            System.out.println(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("总共耗时:" + (end-start) + "毫秒");
    }
}
(3)求出现在的时间
public class CurrentTimeMillisDemo2 {
    public static void main(String[] args) {
        //计算当天的时间
        //总毫秒  距1970年1月1日 00:00 协调世界时间(UTC) 比北京时间早八小时
        long l = System.currentTimeMillis();
        System.out.println(l);

        //求出现在的秒  1s = 1000ms
        long l1 = System.currentTimeMillis()/1000;
        long seconds = l1 % 60;

        //求出现在的分钟
        long l2 = System.currentTimeMillis()/1000/60;
        long minute = l2 % 60;

        //求出现在的小时
        long l3 = System.currentTimeMillis()/1000/60/60;
        long hour = l3 % 24 + 8;//北京时间比协调世界时间晚八小时

        System.out.println(hour + ":" + minute + ":" + seconds);

    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值