zoukankan      html  css  js  c++  java
  • 多线程-上

    多线程两种实现方式:

    一:继承Thread

    public class Student extends Thread {
        @Override
        public void run() {
            for(int i=0;i<7;i++){
                System.out.println("lol");
            }
        }
    }
    public static void main(String[] args) {
            Student stu=new Student();
            stu.start();
            for(int i=0;i<7;i++){
                System.out.println(i);
            }
        }

    二,实现Runnable接口

    public class Student implements Runnable {
        @Override
        public void run() {
            for(int i=0;i<7;i++){
                System.out.println("lol");
            }
        }
    }
    public static void main(String[] args) {
            Student stu=new Student();
            Thread thread=new Thread(stu);
            thread.start();
            for(int i=0;i<7;i++){
                System.out.println(i);
            }
        }

    继承Thread和实现Runnable接口实现多线程的优缺点

    [1] 继承Thread的线程类不能再继承其他类,实现Runnable接口的类还可以继承其他类。

    [2] 实现Runnable接口的线程类,可以让多个线程共享线程实现类的资源

    总结:

    多线程提高了cpu利用率,但程序的复杂度也随之增加。一旦线程开始执行,很难通过其他方式控制线程的轨迹。

    多个线程抢占CPU导致线程的运行轨迹不确定

  • 相关阅读:
    JavaScript
    monkeyrunner总结
    repo简介
    android4.4 settings 中控制卡1 卡2都振动
    卡1卡2设置不同的默认铃声
    获取布局 ActionBar
    android Settings 解析
    设置应用中出现NFC服务,去掉
    判断当前网络显示运营商
    设置中默认铃声 通知 闹钟等
  • 原文地址:https://www.cnblogs.com/zhangxiong-tianxiadiyi/p/10835013.html
Copyright © 2011-2022 走看看