多线程
一、创建线程的步骤:
1 定义一个类继承Thread。
2 重写run方法。
3 创建子类对象,就是创建线程对象。
4 调用start方法,开启线程。让线程执行,同时还会告诉jvm去调用run方法。
二、创建新执行线程有两种方法。
1.一种方法是将类声明为 Thread 的子类。该子类应重写 Thread 类的 run 方法。创建对象,开启线程。run方法相当于其他线程的main方法。
2.另一种方法是声明一个实现 Runnable 接口的类。该类然后实现 run 方法。然后创建Runnable的子类对象,传入到某个线程的构造方法中,开启线程。
三、代码
方法一:
1.测试类
public class Demo02 { public static void main(String[] args) { //创建线程 MyThread mt=new MyThread(); //开启线程 mt.start(); //描述主线程任务 for (int i = 0; i <=100; i++) { System.out.println(Thread.currentThread().getName()+":"+i); } } }
2.自定义线程类
public class MyThread extends Thread{ //重写run方法,来描述线程任务 public void run() { super.run(); for (int i = 0; i <=100; i++) { System.out.println(Thread.currentThread().getName()+":"+i); } } }
方法二:
1.测试类
public class Demo02 { public static void main(String[] args) { //继承thread的方式 Thread th=new Thread(){ public void run() { for (int i = 0; i <100; i++) { System.out.println(Thread.currentThread().getName()+":"+i); } } }; th.start(); //实现接口 Runnable r=new Runnable() { public void run() { for (int i = 0; i <100; i++) { System.out.println(Thread.currentThread().getName()+":"+i); } } }; Thread tg=new Thread(r); tg.start(); } }
2.自定义线程类
public class MyRunnable implements Runnable { public void run() { for (int i = 0; i <100; i++) { System.out.println(Thread.currentThread().getName()+":"+i); } } }
四、相应方法
Thread.currentThread()方法
Thread.currentThread()可以获取当前线程的引用;
一般都是在没有线程对象又需要获得线程信息时通过Thread.currentThread()获取当前代码段所在线程的引用。
getId();获取该线程的标识符
getName();获取该线程名称
getState();获取线程状态
boolean isAlive();测试线程是否属于活动状态
boolean isDaemon();测试线程是否为守护线程
boolean isInterrupted();测试线程是否已经中断

浙公网安备 33010602011771号