多线程
多线程是并发执行代码的,可以解决代码之前的牵绊问题。
并发执行:代码之间在微观上是走走停停的(cpu在这些代码片段之间反复切换执行),宏观上给我们的赶紧是”同时“执行的效果
Thread类是线程类,我们实际开发中使用线程是有两种创建方式
方式1:
定义一个类并继承Thread,然后重写run方法,在run方法中定义线程要执行的任务;
第一种创建线程的方式优点:结构简单,利于使用匿名内部类形式创建 * 缺点: * 1:有继承冲突问题,由于java是单继承的,这导致如果继承了Thread则不能再继承其它类 * 去复用方法了 * 2:我们重写了线程的run方法,并在其中定义了线程要执行的任务,此时该线程就与任务存在 * 了一个必然的耦合关系.这不利于线程的重用.
public class ThreadDemo1{
public static void main(String[]args){
Thread t1 = new Mythread1();
Thread t2 = new Mythread2();
//启动线程要用start;
t1.start;
t2.start;
}
}
class Mythread1 extends Thread{
public vold run(){
for(int i =0; i<1000; i++){
System.out.prinln("你是谁")
}
}
}
class Mythread2 extends Thread{
public vold run(){
for(int i =0; i<1000; i++){
System.out.prinln("我在吃饭")
}
}
}
第二种方法:实现Runnable接口单独定义线程任务
public class ThreadDemo2{
public static void main(String[]args){
//1先实例化要让线程并发执行的任务(Runnable)
Runnale r1 = new MyRunnable();
Runnale r2 = new MyRunnable();
//2创建两条线程来分别执行这两个任务
Thread t1 = new Thread(r1);
Thread t2 =new Thread(r2);
t1.start;
t2.start;
}
}
class MyRunnable implements Runnable{
public void run(){
for(int i =0; i<1000;i++){
System.out.prinln("开门!查水表")
}
}
}