认识线程
概念
- 进程是系统分配资源的最小单位,线程是系统调度的最小单位。
- 一个进程内的线程之间是可以共享资源的。
- 每个进程至少有一个线程存在,即主线程。
线程的创建方式
线程的第一种创建方式
可以通过继承 Thread 来创建一个线程类
public class ThreadDemo1 {
//第一种线程创建方法
static class MyThread extends Thread{
@Override
public void run(){
System.out.println("我是线程1");
//获取到当前线程 并设置线程名
Thread.currentThread().setName("我是自己创建的线程");
try {
Thread.sleep(180*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread thread=new MyThread();
thread.start();
}
}
该方法的好处是 this 代表的就是当前线程,不需要通过
Thread.currentThread() 来获取当前线程的引用。
线程的第二种创建方式
通过实现 Runnable 接口,并且调用 Thread 的构造方法时将 Runnable 对象作为 target 参数传入来创建线程对象。
public class ThreadDemo2 {
static class MyThread2 implements Runnable{
@Override
public void run(){
System.out.println("我是线程2:"+Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread thread=new Thread(new MyThread2());
thread.start();
}
}
}
该方法的好处是可以规避类的单继承的限制;但需要通过 Thread.currentThread() 来获取当前线程的引用。
线程的第三种创建方式
第三种创建方式(lambda表达式)个人推荐
public class ThreadDemo3 {
public static void main(String[] args) {
Thread thread=new Thread(()->{
System.out.println("我是线程3:"+Thread.currentThread().getName());
});
thread.start();
}
}
线程的第四种创建方式
public class ThreadDemo4 {
public static void main(String[] args) {
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("我是线程:"+Thread.currentThread().getName());
}
});
thread.start();
}
}
后两种可做了解。
线程的创建速度
单线程的创建速度
public class ThreadDemo5 {
public static int count=10_1000_0000;
public static void main(String[] args) {
//开始时间
long startTime =System.nanoTime();
int i=0;
int k=0;
for (int j=0;j<count;j++){
i++;
}
for (int j=0;j<count;j++){
k++;
}
//结束时间
long endTime=System.nanoTime();
System.out.println("执行时间:"+(endTime-startTime));
}
}
多线程的创建速度
public class ThreadDemo6 {
public static int count=10_1000_0000;
public static void main(String[] args) throws InterruptedException {
Thread t1=new Thread(()->{
int i=0;
for (int j=0;j<count;j++){
i++;
}
});
Thread t2=new Thread(()->{
int k=0;
for (int j=0;j<count;j++){
k++;
}
});
long startTime=System.nanoTime();
t1.start();
t2.start();
//等待线程执行完
t1.join();
t2.join();
long endTime=System.nanoTime();
System.out.println("执行时间:"+(endTime-startTime));
}
}
通过运行结果的对比 可以发现时间上的差别