文章目录
前言
在华清远见学习的第17天,我们今天学到了线程的知识点,阅读这篇文章,你会学到什么是线程,线程的优点,线程的创建和启动方式等知识点。
一、线程是什么?
线程是指进程中的一个执行流程,一个进程中可以运行多个线程。比如java.exe进程中可以运行很多线程。线程总是属于某个进程,进程中的多个线程共享进程的内存。
二、线程创建和启动方式
1.继承Thread类
创建线程,创建一个自定义类继承Thread类,重写run方法,开启线程创建该类对象,并调用start()方法,等待cpu的工作。
public class MyThread2 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<2000;i++) {
try {
Thread.sleep(1000);
System.out.println(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
MyThread mt= new MyThread();
mt.start();
}
}
2.实现Runnable接口
创建线程:创建一个类实现Runnable接口,实现run方法
开启线程:创建该类对象,再创建Thread类对象,并将该类对象通过构造函数传入Thread类对象。使用Thread类对象调用start方法。
public class MyThread2 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<20;i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args) throws Exception {
MyThread2 mt2 = new MyThread2();
Thread thread = new Thread(mt2);
thread.start();
}
}
3.匿名内部类(为实现Runnable接口的方式变形)
new Thead(new Runnable(){
@Override
public void run(){
线程体...
}
}).start();
public class Test {
public static void main(String[] args) throws Exception {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
4.使用Callable和FutureTask创建线程
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
for (int i = 0; i <= 100; i++) {
System.out.println("加载进度:" + i + "%");
Thread.sleep(100);
}
return "加载完成,正在进入游戏";
}
}
public class Test {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// TODO Auto-generated method stub
MyCallable myCallable = new MyCallable();
FutureTask<String> ft = new FutureTask<String>(myCallable);
Thread thread = new Thread(ft);
thread.start();
System.out.println(ft.get());
}
}
总结
以上就是今天所学习的内容,本文仅仅简单介绍了线程,接下来线程的状态转换下次再分享咯,bye~