首页 > 编程语言 > 详细

java创建多线程

时间:2017-01-22 19:16:37      阅读:169      评论:0      收藏:0      [点我收藏+]

利用Thread 类以及Runnable接口创建线程

package javai;

public class NewThread implements Runnable {

    Thread t;

    public NewThread() {
        t = new Thread(this, "I create a new thread.");
        System.out.println("Child thread:  " + t);
        t.start();
    }

    @Override
    public void run() {

        try {
            for (int i = 0; i < 5; i++) {
                System.out.println("Chinld thead:  " + i);
                Thread.sleep(500);
            }
        } catch (Exception e) {
            System.out.println("Child thead sinterrupted ");
        }
        finally {
            System.out.println("Child thead exiting ");
        }
    }

}

 

 

package javai;

public class ThreadTest {

    public static void main(String[] args) {
        new NewThread();

        try {
            for (int i = 0; i < 5; i++) {
                System.out.println("Main thead:  " + i);
                Thread.sleep(500);
            }
        } catch (Exception e) {
            System.out.println("Main thead sinterrupted ");
        } finally {
            System.out.println("Main thead exiting ");
        }
    }
}

 

 

 

运行结果:

 

Child thread: Thread[I create a new thread.,5,main]
Main thead: 0
Chinld thead: 0
Chinld thead: 1
Main thead: 1
Main thead: 2
Chinld thead: 2
Main thead: 3
Chinld thead: 3
Main thead: 4
Chinld thead: 4
Main thead exiting
Child thead exiting

java创建多线程

原文:http://www.cnblogs.com/anpajin/p/6341219.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!