多线程
概念
单线程:程序中只存在一个线程,没有创建子线程,所有的代码都运行在主线程中
多线程:程序创建了数个子线程,主线程和子线程都同时运行, 目的是更好地使用CPU资源
单线程
~~~ package com;
public class SingletonThread {
public static void main(String[] args) {
Thread thread = Thread.currentThread();
thread.setName("单线程");
System.out.println(thread.getName()+"正在运行");
for (int i = 0; i < 10; i++) {
System.out.println("线程正在休眠:"+i);
try {
thread.sleep(500);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println("线程出现错误!");
}
}
}
}
~~~
多线程
Java中有两种实现多线程的方式:
一、是直接继承Thread类
注意: 继承Thread类必须重写run()方法
~~~ public class Duoxiancheng_Thread { public static void main(String[] args) { System.out.println("主线程ID:"+Thread.currentThread().getName());
MyThread thread = new MyThread(); thread.start(); } }
class MyThread extends Thread{
@Override
public void run() {
System.out.println("子线程ID:"+Thread.currentThread().getName());
}
~~~
注意: 创建好了自己的线程类之后,就可以创建线程对象了,然后通过start()方法去启动线程。不是调用run()方法启动线程
演示:start()方法调用和run()方法调用的区别
~~~ package com.liuyang.first;
public class Star_run { public static void main(String[] args) { System.out.println("主线程ID:"+Thread.currentThread().getId()); DD dd = new DD("thread1"); dd.start(); DD dd2 = new DD("thread2"); dd2.run(); }
}
class DD extends Thread{ private String name;
public DD(String name){
this.name = name;
}
@Override
public void run() {
System.out.println("name:"+name+" 子线程ID:"+Thread.currentThread().getId());
}
}
~~~
从输出结果可以得出以下结论:
1)thread1和thread2的线程ID不同,thread2和主线程ID相同,说明通过run方法调用并不会创建新的线程,而是在主线程中直接运行run方法,跟普通的方法调用没有任何区别;
2)虽然thread1的start方法调用在thread2的run方法前面调用,但是先输出的是thread2的run方法调用的相关信息,说明新线程创建的过程不会阻塞主线程的后续执行。
二、是实现Runnable接口
避免由于Java的单继承特性带来的局限
~~~ package com.liuyang.first;
public class Duoxiancheng_Runnable { public static void main(String[] args) { System.out.println("主线程ID:"+Thread.currentThread().getId()); MyRunnable runnable =