线程的实现
1.在java中,线程的实现由2种
(1).继承Thread类
(2).实现Runnable接口
2.Thread类
Thread类是java.lang包中定义的,继承Thread类必须重写run()方法
定义格式:
class className extends Thread{
run(){}
}
3,Runnable接口
定义格式:
class RunnableName implements Runnable{
run(){}
}
4.Thread类项目结构
(1).
(2).MyThread.java
package thread;
public class MyThread extends Thread{
private String name;
//构造方法传递一个参数来标识我当前是哪一个线程
public MyThread(String name) {
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(name +":"+i);
}
}
}
(3).ThreadDemo.java
package thread;
public class ThreadDemo {
public static void main(String[] args) {
//创建两个线程实现线程的并发机制
MyThread a=new MyThread("A");
MyThread b=new MyThread("B");
a.run();
b.run();
}
}
启动项目截图:
线程应该是并行执行的,说明启动线程不应该是run()方法
调用start()方法启动线程
package thread;
public class ThreadDemo {
public static void main(String[] args) {
MyThread a=new MyThread("A");
MyThread b=new MyThread("B");
//a.run();
//b.run();
a.start();
b.start();
}
}
调用start()方法说明线程并行执行
5.Runnable接口项目结构
(1)
(2).MyRunnable.java
package thread;
import org.omg.CORBA.StringHolder;
public class MyRunnable implements Runnable{
private String name;
//构造方法,用来判断是哪个线程在执行
public MyRunnable(String name) {
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(name+":"+i);
}
}
}
(3).TestDemo.java
package thread;
public class ThreadDemo {
public static void main(String[] args) {
MyRunnable r1=new MyRunnable("A");
MyRunnable r2=new MyRunnable("B");
//因为Runnable接口不存在statrt()启动方法,所以需要新建一个线程
//通过Thread启动
Thread t1=new Thread(r1);
Thread t2=new Thread(r2);
t1.start();
t2.start();
}
}
(4).启动项目截图
说明线程并行执行