线程的概念:
大白话的意思就是,线程存在于进程中,它主要是为了提进程中CPU(进程有内存,线程没有)的利用率,即提高效率。
主线程:执行main方法的线程,是它产生其他线程,通常它是最后结束,因为它要执行关闭其他线程的工作,它不会直接关闭其他线程,而只是发送指令过去。
java实现多线程的方式
- 继承Thread类
- 实现Runnable接口
- 实现Callable接口
java基础学习时实现多线程的方式主要学习前面两种,callable是后面产生的
下面通过一个案例来理解多线程:模拟烧水,洗茶杯与泡茶过程
Demo1:
package test;
import java.util.concurrent.CountDownLatch;
public class ThreadTest {
private static boolean isok = false;
static final CountDownLatch countdown = new CountDownLatch(1);
public static void main(String[] args) {
final Object lock = new Object();
Thread washThread = new Thread(new Runnable() {
public void run() {
for(int i=1;i<=5;i++) {
System.out.println("washing:"+i);
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i==3) {
System.out.println("发出通知");
countdown.countDown();
}
}
}
},"washthread");
Thread boilThread = new Thread(new Runnable() {
public void run() {
try {
countdown.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("收到通知...make tea...");
}
},"boilthread");
washThread.start();
boilThread.start();
}
}
Demo2:
package test;
import java.util.concurrent.CountDownLatch;
public class ThreadTest {
private static boolean isok = false;
static final CountDownLatch countdown = new CountDownLatch(2);
public static void main(String[] args) {
final Object lock = new Object();
Thread washThread = new Thread(new Runnable() {
public void run() {
for(int i=1;i<=5;i++) {
System.out.println("washing:"+i);
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("发出通知");
countdown.countDown();
}
},"washthread");
Thread boilThread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("收到通知...make tea...");
countdown.countDown();
}
},"boilthread");
Thread maketeaThread = new Thread(new Runnable() {
public void run() {
try {
countdown.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("收到通知... 喝茶...");
}
},"maketeathread");
washThread.start();
boilThread.start();
maketeaThread.start();
}
}