zoukankan      html  css  js  c++  java
  • java的线程

    多任务与多线程:多任务属于系统级的各个应用之间的关系,而多线程属于应用级的一个应用的多个功能之间的关系

    创建线程的两种方式:

    实现Runnable接口

    class sunclass {}

    class SumThread extends sumclass imlements Runnable{}

    public class **{public void main(){SumThread st=new SumThread();Thread t=new Thread(st,"threadname");t.start();}} 

    继承Thread类(直接继承thread类,或者使用匿名嵌套类)

    class SumThread extends Thread{
        private long length;
        public SumThread(long length,String name){
            super(name);
            this.length=length;
        }
        public void run(){
            long temp=0;
            for(int i=1;i<=length;i++){
                try {
                    Thread.sleep((int)(Math.random()*10));
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                temp+=i;
            }
            System.out.println(Thread.currentThread()+"zonghe:"+temp);
        }
    }
    public class Thread1 {
        public static void main(String[] args) {
            System.out.println("线程");
            System.out.println(Thread.currentThread());
            SumThread st1=new SumThread(150,"线程1");
            st1.start();
            new Thread("线程2"){
                int length=150;
                public void run(){
                    long temp=0;
                    for(int i=1;i<=length;i++){
                        try {
                            Thread.sleep((int)(Math.random()*10));
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        temp+=i;
                    }
                    System.out.println(Thread.currentThread()+"zonghe:"+temp);
                }
            }.start();
    }}
  • 相关阅读:
    idea2020 安装
    739. 每日温度
    图像翻转
    257. 二叉树的所有路径
    1466. 重新规划路线
    面试题 04.05. 合法二叉搜索树
    671. 二叉树中第二小的节点
    965. 单值二叉树
    648. 单词替换
    137. 只出现一次的数字 II
  • 原文地址:https://www.cnblogs.com/zzy-frisrtblog/p/5463389.html
Copyright © 2011-2022 走看看