jianglilili / jianglilili/Thread

three methods to create thread

Open
#1 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
0
Forks
0
PR merge metrics
No merged PRs in 30d

Description

### 一、继承Thread类创建线程类
直接上码
```
public class FirstThreadTest extends Thread
{
int i=0;

@Override
public void run()
{
for (;i<100;i++)
{
System.out.println(getName() + ": " + i);
}
}

public static void main(String[] args)
{
for (int i=0;i<100;i++)
{
System.out.println(Thread.currentThread().getName() + " : " + i);
}
new FirstThreadTest().start();
new FirstThreadTest().start();
}
}

```

- 上述代码中Thread.currentThread()方法返回当前正在执行的线程对象。GetName()方法返回调用该线程的名字

### 二、通过Runnable接口创建线程类
直接上码
```
public class RunnableThreadTest implements Runnable
{
private int i=0;

@Override
public void run()
{
for (;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+":"+i);
}
}

public static void main(String[] args)
{
for (int i=0;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+":"+i);
if (i==20)
{
RunnableThreadTest run=new RunnableThreadTest();
new Thread(run,"新线程1").start();
new Thread(run,"新线程2").start();
}
}
}
}

```
### 三、通过Callable和Future创建线程

1. 创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。

2. 创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。

3. 使用FutureTask对象作为Thread对象的target创建并启动线程。

4. 调用FutureTask对象的get()方法来获得子线程执行结束后的返回值

上码
```
public class CallableThreadTest implements Callable
{
public static void main(String[] args)
{
CallableThreadTest ctt=new CallableThreadTest();
FutureTask ft=new FutureTask<>(ctt);
for (int i=0;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+"循环变量i的值"+i);
if (i==20)
{
new Thread(ft," 有返回值的线程").start();
}

}
try
{
System.out.println("子线程的返回值"+ft.get());
}catch (InterruptedException e)
{
e.printStackTrace();
}catch (ExecutionException e)
{
e.printStackTrace();
}
}

@Override
public Integer call() throws Exception
{
int i=0;
for (;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+":"+i);
}
return i;
}
}

```

### 附录:创建线程的三种方式的对比

**1. 采用实现Runnable、Callable接口的方式创建多线程**

- 优势

线程类只是实现了Runnable接口或Callable接口,还可以继承其他类。
在这种方式下,多个线程可以共享同一个target对象,所以非常适合多个相同线程来处理同一份资源的情况,从而可以将CPU、代码和数据分开,形成清晰的模型,较好地体现了面向对象的思想

- 劣势

编程稍微复杂,如果要访问当前线程,则必须使用Thread.currentThread()方法

**2. 使用继承Thread类的方式创建多线程**

- 优势

编写简单,如果需要访问当前线程,则无需使用Thread.currentThread()方法,直接使用this即可获得当前线程。

- 劣势

线程类已经继承了Thread类,所以不能再继承其他父类

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.