韩顺平 java 第39讲 线程

来源:互联网 发布:2017淘宝爆款打造方法 编辑:程序博客网 时间:2024/04/29 20:49

多个线程

package com.chen;public class MyClass {    public static void main(String[] args) {        Cat cat = new Cat();        Dog dog = new Dog();        //创建一个Thread对象        Thread t1 = new Thread(cat);        Thread t2 = new Thread(dog);        t1.start();        t2.start();    }}class Cat implements Runnable{    public void run(){        int i = 0;        while(i < 10){            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            System.out.println("Cat:" + i);            ++i;        }    }}class Dog implements Runnable{    public void run(){        int j = 0;        while(j < 10){            try {                Thread.sleep(700);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            System.out.println("Dog:" + j);            ++j;        }    }}

所以我们尽可能的使用实现Runnable接口的方式来创建线程。

0 0