代码改变世界

Java 多线程

2016-11-23 11:12  甘雨路  阅读(136)  评论(0编辑  收藏  举报
package com.lf.threadhomework;

public class TestHomework {

    public static void main(String[] args) {
        // 打印奇数的线程
        OddNumberThread oddNumberThread = new OddNumberThread();
        oddNumberThread.start();
        
        // 打印0~100的线程
        NumberThread numberThread = new NumberThread("打印0~100的线程");
        numberThread.start();
        
        //打印偶数的线程
        EvenNumberThread evenNumberThread = new EvenNumberThread();
        Thread thread = new Thread(evenNumberThread);
        thread.start();
    }

}

class OddNumberThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i%2==1) {
                System.out.println("打印0~100之间的奇数:"+i);
            }
        }
    }
    public OddNumberThread(){
        super();
    } 
}

class NumberThread extends Thread{
    public String threadName;
    public NumberThread(String name) {
        // TODO Auto-generated constructor stub
        threadName = name;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 0; i < 100; i++) {
                System.out.println(threadName+i);
        }
    }
}

class EvenNumberThread implements Runnable{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 0; i < 100; i++) {
            if (i%2==0) {
                System.out.println("打印0~100之间的偶数:"+i);
            }
        }
    }
}