/**
* 多线程
* duoxianc可以并发执行多个代码片段,使得代码有机会“同时进行”。
* <p>
* 线程的创建有俩种方式:
* 1:继承Thread并重写run方法
*/
public class ThreadDemo1 {
public static void main(String[] args) {
Thread thread=new MyThead1();
Thread thread1=new MyThead2();
Thread thread2=new MyThead3();
/*
启动线程要调用start方法,而不是直接调用run方法
当启动start方法调用线程会纳入到线程调度器中,一旦获取到了
时间片,run方法会自动被执行
*/
thread.start();
thread1.start();
thread2.start();
}
}
/**
* 第一种创建线程的方式优点在于:结构简单,利于匿名内部类的创建
* 缺点有俩个:
* 1。继承Thread,由于是单继承,这导致如果继承了Threa就无法再
* 继承其他类来复用代码,实际开发中很不方便
* 2:定义线程的同重写了run方法来定义线程要定义的任务,这导致线程与
* 线程要执行的任务存在这必然的绑定关系,不利于线程的重用
*/
class MyThead1 extends Thread {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("你是谁!");
}
}
}
class MyThead2 extends Thread {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("查水表的!");
}
}
}
class MyThead3 extends Thread {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("开门没水了!");
}
}
}
第二种方式
package thread; /** * 第二种 */ public class ThreadDemo2 { public static void main(String[] args) { //单独定义线程任务 Runnable r1=new MyRunable1(); Runnable r2=new MyRunable2(); //创建线程 Thread t1=new Thread(r1); Thread t2=new Thread(r2); t1.start(); t2.start(); } } class MyRunable1 implements Runnable{ public void run(){ for (int i=9;i<10000;i++){ System.out.println("来了老哥!"); } } } class MyRunable2 implements Runnable{ public void run(){ for (int i=9;i<10000;i++){ System.out.println("进来玩啊!"); } } }