(一)Thread类
1.结构
java.lang.Object
|---java.lang.Thread
2.创建线程的两种方法
(1)一种方法是将类声明为Thread的子类,该子类应重写Thread类的run方法
class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
PrimeThread p = new PrimeThread(143);
p.start();
(2)创建线程的另一种方法是声明实现Runnable接口的类,然后该类实现run方法。然后可以分配该类的实例,在创建Thread时作为一个参数来传递并启动
(3)这种方法给已经实现继承的类,提供了实现多线程的扩展方法,实现接口
class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
PrimeRun p = new PrimeRun(143);
new Thread(p).start();
代码1:第一种创建线程的方法
MyThread类
// 1.继承Thread类
public class MyThread extends Thread{
private String threadName;
public MyThread() {
super();
}
// 提供一个有参的构造法方法,把名字传给父类的构造方法直接传递一个线程的名字
public MyThread(String threadName) {
super(threadName);
this.threadName = threadName;
}
// 2.重写run方法
@Override
public void run() {
for(int i=0;i<5;i++) {
System.out.println(this.getName()+": hello : "+i);
}
}
}
Main
public class Main {
public static void main(String[] args) {
//no_parameter_construction_method();
threadName_construction_method();
}
/**
* 1.调用无参数的构造方法创建线程对象和设置线程名字
* */
public static void no_parameter_construction_method() {
// 3.创建线程的实例对象
MyThread my1=new MyThread();
MyThread my2=new MyThread();
// 4.可以设置线程的名字,不设置默认使用JVM给分配的名字(Thread-N)
my1.setName("线程1");
my2.setName("线程2");
// 5.启动线程
// 调用run()的话,的就是单纯的调用方法
// 调用线程应该使用start()方法
my1.start();
my2.start();
System.out.println("end");
}
public static void threadName_construction_method() {
// 3.创建线程的实例对象
MyThread my3=new MyThread("线程3");
MyThread my4=new MyThread("线程4");
// 4.启动线程
my3.start();
my4.start();
System.out.println("end");
}
}
代码1:第二种创建线程的方法
OurThread类
// 1.实现Runnable接口
public class OurThread implements Runnable{
// 2.重写run方法
@Override
public void run() {
for(int i=0;i<10;i++) {
// 3.获取当前线程名字
System.out.println(Thread.currentThread().getName()+": 你好 : "+i);
}
}
}
Main
public class Main {
public static void main(String[] args) {
// 这2个方法调用,不会等待上一个方法完事后,下一个方法才开始,而是不阻塞直接就开始
createThread();
createNameThread();
}
public static void createThread() {
// 4.创建实现接口类对象
// 5.创建线程
OurThread ot1=new OurThread();
Thread t1=new Thread(ot1);
OurThread ot2=new OurThread();
Thread t2=new Thread(ot2);
t1.start();
t2.start();
System.out.println("end");
}
public static void createNameThread() {
// 4.创建实现接口类对象
// 5.创建线程,可以带名字,不带则使用JVM默认分配的名字
OurThread ot1=new OurThread();
Thread t1=new Thread(ot1,"线程01");
OurThread ot2=new OurThread();
Thread t2=new Thread(ot2,"线程02");
t1.start();
t2.start();
System.out.println("end");
}
}
转载于:https://blog.51cto.com/13634837/2091795