厦门营销型网站,您提交的网站域名无备案,wordpress首页标题代码,建网平台上篇博客我们介绍了一些基本概念#xff0c;进程、线程、并发。下面我们开始写第一个多线程的程序。两种方式#xff1a;一、实现Runnable接口#xff1b;二、基础Thread类。一、实现Runnable接口package com.tgb.klx.thread;public class hello1 implements Runnable {publ…上篇博客我们介绍了一些基本概念进程、线程、并发。下面我们开始写第一个多线程的程序。两种方式一、实现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接口的方式可能更灵活一点。原文http://blog.csdn.net/kanglix1an/article/details/46006093