zoukankan      html  css  js  c++  java
  • 多线程简单实例(0)

    创建线程有两种方式:1.继承Thread类 2,实现Runnable接口

    优缺点:

    如果继承Thread,由于java不能多继承,所以无法继承别的类。当然有点就是有很多继承自Thread的方法,方便使用

    实现Runnable接口很方便,而且可以继承别的类。缺点就是功能单一。

    下面是一个简单的多线程实例。两种方式创建线程类。但是,这个程序的重点不在这,而是线程执行的顺序和过程。

    package test;
    
    public class ThreadTest {
        public static void main(String[] args) {
            ThreadDemo thread  = new ThreadDemo();
            RunnableTest test = new RunnableTest();
            Thread test2 = new Thread(test);
            //thread.run();
            thread.start();
            test.run();
            test2.start();
            while(true) {
                System.out.println("all Thread is die");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if(!thread.isAlive() && !test2.isAlive())
                    break;
            }
            
        }
    }
    
    class ThreadDemo extends Thread {
        @Override
        public void run() {
            System.out.println("Thread:"+Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    class RunnableTest implements Runnable{
    
        @Override
        public void run() {
            System.out.println("this is the test class:"+Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }

    执行结果:

    Thread:Thread-0
    this is the test class:main
    all Thread is die
    this is the test class:Thread-1
    all Thread is die
    all Thread is die
    all Thread is die
    all Thread is die
    all Thread is die
    all Thread is die
    all Thread is die
    all Thread is die
    all Thread is die

  • 相关阅读:
    P4146 序列终结者(Splay树)
    P2617 Dynamic Rankings(树套树)
    P4168 [Violet]蒲公英(分块魔术)
    P3649[APIO2014]回文串(回文自动机)
    [IOI2011]Race(树上启发式合并)
    CentOS 7安装 .net core 环境 官网说明地址
    宝塔 Linux 面板php.ini文件在哪个目录
    KPPW部署一直提示No input file specified的Apache伪静态设置
    【分享】 MPSoC的VCU超频
    Versal AIE 上手尝鲜 2 -- Linux例程
  • 原文地址:https://www.cnblogs.com/justenjoy/p/7044342.html
Copyright © 2011-2022 走看看