zoukankan      html  css  js  c++  java
  • 如何实现多线程

    1.继承Thread类实现多继承(此法优缺点,若已经继承类,则无法再继承Thread类);

    public class TestThread extends Thread {//自定义类继承Thread类
        //run()方法里是线程体
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println(this.getName() + ":" + i);//getName()方法是返回线程名称
            }
        }
     
        public static void main(String[] args) {
            TestThread thread1 = new TestThread();//创建线程对象
            thread1.start();//启动线程
            TestThread thread2 = new TestThread();
            thread2.start();
        }
    }


    2.通过Runnable接口实现多继承

    public class TestThread2 implements Runnable {//自定义类实现Runnable接口;
        //run()方法里是线程体;
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
        public static void main(String[] args) {
            //创建线程对象,把实现了Runnable接口的对象作为参数传入;
            Thread thread1 = new Thread(new TestThread2());
            thread1.start();//启动线程;
            Thread thread2 = new Thread(new TestThread2());
            thread2.start();
        }
    }

    步骤:先创建线程对象,然后启动线程对象


  • 相关阅读:
    校验文件数字签名的合法性(VerifyPE)
    windbg help
    VIM的常用操作
    使用Jsonp解决跨域数据访问问题
    Linux下不同文件编码的转换
    Segoe Font 介绍
    关于框架的一些思考
    Linux下Aptana Plugin For Eclipse的破解
    增强网站易用性的10个设计技巧
    Firebug中的console tab使用总结
  • 原文地址:https://www.cnblogs.com/timeboy/p/9464439.html
Copyright © 2011-2022 走看看