java中多线程简介及其实例
1、如何创建线程 在Java语言中已经将线程的底层封装的比较友好了,我们可以通过 Java提供的类,非常快速就可以创建出线程。 第一种方式 继承 Thread 类

2、package javaseday09;
/** * 使用继承 Thread类的方式来创建线程 */public class ThreadDemo1 { public static void main(String[] args) { //创建线程 Thread t1=new MyThread1(); Thread t2=new MyThread2(); //启动线程 /** * 调用 start 方法 CPU会自己去执行 * 2个线程 */ t1.start(); t2.start(); }}

3、class MyThread1 extends Thread { // 重写 Thread 中的 run方法 // run方法是线程工作的内容 public void run() { for(int i=0;i<100;i++) { System.out.println("你是谁啊?"); } }}
class MyThread2 extends Thread { //线程2工作的内容 public void run() { for(int i=0;i<100;i++) { System.out.println("开门,查水表!"); } }}

4、第二种方式 实现 Runnable 接口 package javaseday09;/** * 使用实现 runnable接口来做线程 * 使用Runnable接口实现线程的好处 * 1.解除线程与线程功能的耦合 * 2.保留类的继承特性 */public class ThreadDemo2 { public static void main(String[] args) { Runnable r1=new MyRunnable1(); Runnable r2=new MyRunnable2(); Thread t1=new Thread(r1); Thread t2=new Thread(r2); t1.start(); t2.start(); }}

5、class MyRunnable1 implements Runnable{ public void run() { for(int i=0;i<10;i++) { System.out.println("你是谁啊?"); } }}class MyRunnable2 implements Runnable{ public void run() { for(int i=0;i<10;i++) { System.out.println("开门查水表?"); } }}

6、package javaseday09;/** * Thread.yield(); * 模拟CPU的时间片没有了 */public class ThreadDemo3 { public static void main(String[] args) { Thread t1=new Thread() { public void run() { for(int i=0;i<10;i++) { System.out.println("你是谁啊?"); //模拟CPU给该线程分配的时间用完了 Thread.yield(); } } }; Runnable run=new Runnable() { public void run() { for(int i=0;i<10;i++) { System.out.println("开门,社区送温暖!"); Thread.yield(); } } }; Thread t2=new Thread(run); //启动线程 t1.start(); t2.start(); }}
