JAVA多线程

JAVA多线程

1.使用Runnable接口方式创建线程

2.使用匿名类方式创建线程

3.线程常用api

4.守护线程与非守护线程

5.线程几种状态

6.join方法介绍

 

 

1.使用Runnable接口方式创建线程

代码

1.1实现Runnable run方法

class CreateThreadDemo02 implements Runnable {

public void run() {
// 具体的线程需要执行的任务
System.out.println("子线程开始启动....");
for (int i = 0; i < 30; i++) {
System.out.println("run i:" + i);

创建main方法调用子线程 Runnable 接口不能直接使用start方法需要创建threat对象

public static void main(String[] args) {
CreateThreadDemo02 createThreadDemo02 = new CreateThreadDemo02();
Thread thread = new Thread(createThreadDemo02);
thread.start();
System.out.println("主线程开始启动....");
for (int i = 0; i < 5; i++) {
System.out.println("main i=" + i);
}
System.out.println("主线程执行完毕....");

思考是使用threa继承好还是使用Runnable接口好

因为我们是对象接口进行编程,而且是单继承多实现 所有使用Runnable接口的方式使用多继承比较好

 

2.使用匿名类方式创建线程

2.1首先我们需要在一个类中创建一个类称为类部类、

2.2创建main方法创建threa实现Runnable run 方法 执行线程

public static void main(String[] args) {

Thread thread = new Thread(new Runnable() {

@Override
public void run() {
// 线程需要执行的任务代码
System.out.println("子线程开始启动....");
for (int i = 0; i < 30; i++) {
System.out.println("run i:" + i);
}
}
});
thread.start();
System.out.println("主线程开始启动....");
for (int i = 0; i < 5; i++) {
System.out.println("main i=" + i);
}
System.out.println("主线程执行完毕....");
// 创建的线程,为和主线程并行执行。
}

3.线程常用api

3.1getId() 线程的id 唯一, 不会重复 使用方式

System.out.println("线程id:" + getId() + ":子线程 ,i:" + i );

3.2stop();// 不安全。不建议大家使用 线程死亡方法 使用方式因为stop方法不管代码执行在哪直接死亡

 Thread.currentThread().stop();

3.3Thread.currentThread() 获取到当前线程的 id name 当前线程死亡、

System.out.println("主线程:" + Thread.currentThread().getId() );获取当前线程ID

System.out.println("name:" + Thread.currentThread().getName()); 获取当前线程name 

Thread.currentThread().stop();  当前线程死亡

 

4.守护线程与非守护线程GC线程

 

 

GC线程主要收取线程垃圾主要收取主线程

守护线程使用方式、对象名.setDaemon(true);

t1.setDaemon(true);//t1该线程为守护线程 如果主线程执行完毕则一起销毁

非守护线程和主线程互不影响

 

5.线程几种状态

5.1准备状态   创建线程

5.2就绪状态   调用start等待运行

5.3运行状态   开始运行

5.4休眠状态  调用sleep方法,转到就绪状态

5.5死亡状态  调用stop方法死亡

 

 

 6.join方法介绍

6.1 如果线程对象调用join方法将等待其他待的线程执行完毕在执行,使用方法如下


public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {

public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("T1,i:" + i);
}
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {

public void run() {
try {
t1.join();
} catch (Exception e) {
// TODO: handle exception
}
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(30);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("T2,i:" + i);
}
}
});

t2.start();
Thread t3 = new Thread(new Runnable() {

public void run() {
try {
t2.join();
} catch (Exception e) {
// TODO: handle exception
}
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(30);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("T3,i:" + i);
}
}
});

t3.start();

posted @ 2020-01-10 23:01  红红蓝蓝  阅读(119)  评论(0编辑  收藏  举报