zoukankan      html  css  js  c++  java
  • JAVA基础(多线程Thread和Runnable的使用区别(转载)

      转自:http://jinguo.iteye.com/blog/286772

    Runnable是Thread的接口,在大多数情况下“推荐用接口的方式”生成线程,因为接口可以实现多继承,况且Runnable只有一个run方法,很适合继承。

    在使用Thread的时候只需要new一个实例出来,调用start()方法即可以启动一个线程。
    Thread Test = new Thread();
    Test.start();

    在使用Runnable的时候需要先new一个继承Runnable的实例,之后用子类Thread调用。
    Test impelements Runnable
    Test t = new Test();
    Thread test = new Thread(t);

    在某个题目里,需要分别打印出a与b各10次,并且每打印一次a睡1秒,打印一次b睡2秒。

    可以在run方法外面定义String word与int time
    之后用
    Thread t1 = new Thread();
    Thread t2 = new Thread();

    t1.word = "a"
    t1.time = 1000

    t2.Word = "b"
    t2.time = 2000

    t1.start();
    t2.start();

    ----Runnable的代码

    class T implements Runnable{
    String s = "";
    int time = 0;
    public void run (){
       for (int i=0;i<10;i++) {
        try {
         Thread.sleep(time);
        } catch (InterruptedException e) {
         Thread.interrupted();
        }
        System.out.println(s);
       }
    }
    }
    public class Test {
    public static void main(String[] args) {
       T t1 = new T();
       T t2 = new T();
       t1.s = "a";
       t1.time = 100;
       t2.s = "b";
       t2.time = 200;
       Thread a = new Thread(t1);
       a.start();
       Thread b = new Thread(t2);
       b.start();
     
    }
    }

  • 相关阅读:
    SoapUI开源版简单定制报告1
    python json模块 字典 输出中文
    Django文件上传机制用法详解(转)
    选择排序
    插入排序
    Python单元测试框架 unittest
    Design Pattern —— Prototype /Template Method/Iterator/Composite/Bridge
    Design Pattern ——Factory Method&Abstract Factory
    Design Pattern ——Builder
    JAVA泛型那些事儿
  • 原文地址:https://www.cnblogs.com/lance-ehf/p/4010387.html
Copyright © 2011-2022 走看看