什么是多线程
多个任务可以同时运行
- 进程 独立的内存地址空间
- 线程 进程内部的独立执行路径,它们共享内存地址空间
线程的生命周期:
1. 新建: new Thread();
2. 就绪:调用start();之后,run()之前
3. 执行:run();运行
4. 中段:a.因为优先级。b.使用sleep()方法(睡眠)。c.调用wait()/notify()方法(等待/唤醒)。d.调用yield()方法(挂起)。e.等待I/O事件!
其中,sleep()到点时候醒过来,不代表醒过来就被CPU执行,而是到点醒过来后该线程重新参与CPU竞争
多线程的实现方式
线程类的实现方式一
通过继承Thread类
public class MyThread extends Thread{
private String msg;
public MyThread() {
// TODO Auto-generated constructor stub
super();//新建状态
this.start();
}
public MyThread(String msg){
super();
this.msg = msg;
// this.setPriority(Thread.MAX_PRIORITY);
this.start();
}
//run方法相当于子线程的main方法
@Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0; i < 100; i++){
System.out.println(msg + "*********" + i);
}
}
线程的实现方式二
通过实现Runnable接口
public class YourThread implements Runnable{
private String msg;
public YourThread(){
Thread th = new Thread(this);//新建状态
th.start();
}
public YourThread(String msg){
this.msg = msg;
Thread th = new Thread(this);
// th.setPriority(Thread.MIN_PRIORITY);
th.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0; i < 100; i++){
System.out.println(msg + "-----" + i);
}
}
线程的运行
- main方法所在的线程—主线程
- 主线程可以开启子线程
- start方法才是开启线程,它会自动调用run方法
线程安全性问题
当多个线程操作同一对象的时候,有可能会造成数据的混乱。
此时应当在操作对象的步骤 用synchronized关键字 使线程同步。