实现多线程以及多线程的各种方法
1.实现多线程的两种方法
1.1继承Thread类
package muilthread.programming.test;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* 继承Thread类
*/
MyThread thread1 = new MyThread();
Thread thread = new Thread(thread1);
thread.setName("线程0");
thread.start();
thread1.setName("线程1");
thread1.start();
/**
* main线程
*/
System.out.println(Thread.currentThread().getName()+":"+"结束了");
}
}
/**
* 继承Thread类
* @author DarkSouls
*
*/
class MyThread extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":运行了");
}
}
}
上述代码实现了继承Thread类并且重写了run方法,用两种不同的形式实现了继承Thread类
运行结果如下图:
1.2实现Runnable接口
package muilthread.programming.test;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* 实现Runnable接口
*/
Runnable Runnable = new MyThreadOfRunnable();
Thread thread2 = new Thread(Runnable);
thread2.start();
thread2.setName("线程2");
/**
* main线程
*/
System.out.println(Thread.currentThread().getName()+":"+"结束了");
}
}
/**
* 实现Runnable接口
* @author DarkSouls
*
*/
class MyThreadOfRunnable implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName()+":运行了");
}
}
以上代码实现了Runnable接口,先创建实现了Runnable接口的类对象,然后在线程创建的时候传入线程的构造方法
运行结果如下:
线程的构造方法如下:
2.多线程中的基本方法
2.1 start()方法
基本内容:
start()方法意思为启动线程,意味着一个线程的开始,即执行类中重写的run()方法。
2.1.1 线程的start()方法和直接调用run方法的区别
直接调用run方法只会串行执行代码,不会像start()方法一样异步执行
package muilthread.programming.test;
public class 直接调用Run方法是start方法 {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread thread0 = new MyThread();
thread0.setName("start方法");
thread0.start();
thread0.run();System.out.println("第一次run方法执行");
thread0.run();System.out.println("第二次run方法执行");
}
}
结果如下:
线程类创建是本文中的线程类1.1的线程类,可见线程的run方法调用是根据在main函数中的顺序,是串行执行的。
2.2 currentThread()方法
这个方法可返回代码段正在被哪个线程调用的信息,如同在1.1例子中获得线程设置的名字一样
Thread.setName(String name);这个方法就是设置这个线程的名字
2.3 isAlive()方法
判断当前的线程是否处于活动状态
活动状态就是线程以及启动且尚未终止,线程处于正在运行或准备开始的状态,就认为线程是“存活”的。
2.4 getId()方法
getId方法是取得线程的唯一标识。