简单的java多线程源码分享(一)

//创建一个女演员线程
//使用实现Runnable接口方式创建
public class Acress implements Runnable {

//重写run方法
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"是一个演员");
        int count = 0;
        //线程启动/关闭标识
        boolean keepRunning = true;
        while(keepRunning){
            System.out.println(Thread.currentThread().getName()+"登台演出:"+(++count));
            if (count == 100) {
                keepRunning = false;
            }
            if (count%10 == 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(Thread.currentThread().getName()+"的演出结束了");
    }

//创建一个男演员线程
//使用继承Thread对象创建
public class Actor extends Thread{
    public void run(){
        System.out.println(getName()+"是一个演员");
        int count = 0;
        boolean keepRunning = true;
        while(keepRunning){
            System.out.println(getName()+"登台演出:"+(++count));
            if (count == 100) {
                keepRunning = false;
            }
            if (count%10 == 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(getName()+"的演出结束了");
    }

    public static void main(String[] args) {
        Thread actor = new Actor();
        actor.setName("Mr.Thread");
        actor.start();
        Thread actress = new Thread(new Acress(),"Ms.Runnable");
        actress.start();
    }
posted @ 2017-03-16 22:47  gent95  阅读(98)  评论(0编辑  收藏  举报