day23文字笔记
1.什么是线程?
一条线程就是一组任务执行序列
2.什么是多线程?
多线程就是在某一个时间段并发多个任务执行序列
3.为什么需要多线程?
多线程可以“同时”运行多个任务,有效利用资源,让使用者有更好的使用体验
由于硬件决定了多个代码片段不是真正意义上的同时执行,只是模拟这样的操作,实际上多个代码片段都是走走停停的,
但是感官上是同时运行这种执行方式称为“并发”
4.如何创建多线程?
第一种方式:
public class ThreadDemo1 {
public static void main(String[] args) {
Thread t1 = new MyThread1();
Thread t2 = new MyThread2();
public class ThreadDemo2 {
public static void main(String[] args) {
//创建任务实例
Runnable r1 = new MyRunnable1();
Runnable r2 = new MyRunnable2();
//创建线程
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
class MyRunnable1 implements Runnable{
public void run(){
for (int i =0;i<=1000;i++){
System.out.println(“你是谁啊”);
}
}
}
class MyRunnable2 implements Runnable{
public void run(){
for (int i =0;i<=1000;i++){
System.out.println(“我是查水表的”);
}
}
}
案例:
public class ThreadDemo3 {
public static void main(String[] args) {
//第一种方式:继承Thread重写run方法
Thread t1 = new Thread(() -> {
for (int i =0;i<=1000;i++){
System.out.println(“你是谁啊”);
}
});
Runnable r2 = new Runnable() {
public void run() {
for (int i =0;i<1000;i++){
System.out.println("我是查水表的");
}
}
};
Thread t2 = new Thread(r2);
//第二种方式:实现Runnable接口重写run方法单独定义任务
t1.start();
t2.start();
}
}
5.分配线程
public class CurrentThreadDemo {
public static void main(String[] args) {
//获取主线程
Thread main = Thread.currentThread();
System.out.println(“主线程:”+main);
dosome();
System.out.println(“main方法执行完了,”+main+“执行完毕了”);
}
private static void dosome() {
Thread t = Thread.currentThread();
System.out.println(“执行dosome方法的线程是”+t);
}
}



