多线程--Thread类
1.定义类继承Thread类
2.重写run方法,run方法中的代码就会按照多线程机制进行调用和执行;
3.在main方法中定义类的对象,调用start()方法启动线程,会自动调用run方法
public class MyThread1 extends Thread{
@Override
public void run() {
for (int i=0;i<100;i++){
System.out.println("执行听歌..."+i);
}
}
public class MyThread2 extends Thread{
@Override
public void run() {
for (int i=0;i<100;i++){
System.out.println("执行打游戏..."+i);
}
}
public static void main(String[] args) {
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
//线程类不需要调用run方法,只需要调用start()方法启动线程,自动就会执行run方法
t1.start();
t2.start();
}
Runnable接口
1.定义类实现Runnable接口;
2.重写run方法;
3.在main方法中实例化Runnable接口的实现类对象;
4.定义两个线座Thread类的对象,把Runnable 接口的实现对象传入构造方法中;
5.线程类对家调用start方法,启动线程,自动执iRunnable接口的实现类中的run方法;
public class MyRunnable1 implements Runnable{
@Override
public void run() {
for (int i=0;i<100;i++){
System.out.println("Runnable执行听歌..."+i);
}
}
}
public class MyRunnable2 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("Runnable执行打游戏..."+i);
}
}
}
public static void main(String[] args) {
MyRunnable1 r1=new MyRunnable1();
MyRunnable2 r2=new MyRunnable2();
//Runnable接口的实现多线程,必须借助Thread类才能实现
Thread t1=new Thread(r1);
Thread t2=new Thread(r2);
t1.start();
t2.start();
}
多线程
线程是进程中的一个执行单元,负责当前进程中程序的执行, -个进程中至少有一个线程。一个进程
中是可以有多个线程的,这个应用程序也可以称之为多线程程序。
Thread类这种显示机制导致自定义的类没办法在继承别的类
Runnable接口的机制可以让自定义类既可以继承别的类,也可以实现多线程。