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

来源:互联网 发布:linux解压bz2文件 编辑:程序博客网 时间:2024/06/05 07:06

上篇博客我们介绍了一些基本概念,进程、线程、并发。下面我们开始写第一个多线程的程序。

 

两种方式:一、实现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;}


运行结果:


二、基于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;}


运行结果:


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

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

 

总结:

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


1 0
原创粉丝点击