线程:
进程、线程都是实现并发机制的有效手段。
线程是比进程更小的执行单位,是在进程基础上的进一步划分。
一个程序运行,可能多个线程同时运行。
Thread类
Thread类属于java.lang.Object。在文档中的定义:public class Thread extends Object implements Runnable
可以看出,Thread类也实现了Runnable接口,一个类要继承thread类必须重写run()方法。
- public class MyThread extends Thread{
- private String name;//再类中定义一个属性
- public MyThread(String name){
- this.name = name;
- }
- // 一定要重写Thread类中的run()方法,此方法为线程的主体
- public void run(){
- for(int i=0; i<10; i++){
- System.out.println(name+"运行, i="+i);
- }
- }
- }
- public class ThreadDemo01 {
- public static void main(String[] args) {
- MyThread mt1 = new MyThread("线程A");
- MyThread mt2 = new MyThread("线程B");
- mt1.run();
- mt2.run();
- }
- }
Runnable接口
- public class MyThread2 implements Runnable{
- private String name;
- public MyThread2(String name){
- this.name = name;
- }
- // 重写Runnable接口中的run()方法
- public void run(){
- for(int i=0; i<10; i++){
- System.out.println(name+"运行, i="+i);
- }
- }
- }
- public class ThreadDemo04 {
- public static void main(String[] args) {
- MyThread2 mt1 = new MyThread2("线程A");
- MyThread2 mt2 = new MyThread2("线程B");
- Thread t1 = new Thread(mt1);
- Thread t2 = new Thread(mt2);
- t1.start();
- t2.start();
- }
- }