设为首页 加入收藏

TOP

Java并发编程--多线程之HelloWorld
2015-07-16 12:56:16 来源: 作者: 【 】 浏览:8
Tags:Java 并发 编程 线程 HelloWorld

两种方式:一、实现Runnable接口;二、基础Thread类。


一、实现Runnable接口


package com.tgb.klx.thread;


public class hello1 implements Runnable {


?public hello1() {


?}


?public hello1(String name) {
? this.name = name;
?}


?public void run() {
? for (int i = 0; i < 5; i++) {
? ?System.out.println(name + "运行? ? " + i);
? }
?}


?public static void main(String[] args) {
? hello1 h1 = new hello1("线程A");
? Thread demo1 = new Thread(h1);
? hello1 h2 = new hello1("线程B");
? Thread demo2 = new Thread(h2);
? demo1.start();
? demo2.start();
?}


?private String name;


}


运行结果:


Java并发编程--多线程之HelloWorld


二、基于Thread类


package com.tgb.klx.thread;
public class hello2 extends Thread {


?public hello2() {


?}


?public hello2(String name) {
? this.name = name;
?}


?public void run() {
? for (int i = 0; i < 5; i++) {
? ?System.out.println(name + "运行? ? " + i);
? }
?}


?public static void main(String[] args) {
? hello2 h1 = new hello2("A");
? hello2 h2 = new hello2("B");
? h1.start();
? h2.start();
?
?}


?private String name;
}


运行结果:


Java并发编程--多线程之HelloWorld


实现Runnable接口的方式,需要创建一个Thread类,将实现runnable的类的实例作为参数传进去,启动一个线程,如果直接调用runnable的run方法跟调用普通类的方法没有区别,不会创建新的线程。


Thread类实现了Runnable接口,Thread类也有run方法,调用Thread的run方法同样也不会新建线程,和调用普通方法没有区别,所以大家在使用多线程时一定要注意。


总结:


以上两种方式都可以实现,具体选择哪种方式根据情况决定。java里面不支持多继承,所以实现runnable接口的方式可能更灵活一点。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java并发编程--进程与线程 下一篇Java--反射之获取对象信息

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: