Java-----------多线程(一个继承多个实现)
特点:高并发、高可用、高性能
应用:双十一几十万人秒杀商品、抢火车票等,既要保证这么多人可以同时抢 又要保证抢得到。
概念:在操作系统中的程序就是进程(看视频,有图像,声音、字幕)
创建线程:
- 继承Thread类
- 实现Runnable接口
- 实现Callable接口
public class Thre extends Thread {//继承Thread类
public void run() {//线程路口
for (int i = 0; i < 20; i++) {
System.out.println("第一个线程");
}
}
public static void main(String[] args) {
Thre d = new Thre();
d.start();//启动线程
for (int i = 0; i < 20; i++) {
System.out.println("0000001");
}
}
}
即可实现两线程同时运行。
买车票:
public class ThreadDemo {
public static void main(String[] args) {
TeseThread3 t = new TeseThread3();//创建对象
new Thread(t, "Thread-0").start();
new Thread(t, "Thread-1").start();
new Thread(t, "Thread-2").start();
new Thread(t, "Thread-3").start();
}
static class TeseThread3 implements Runnable {//实现Runnable类
private volatile int tickets = 100;
String str = new String();
public void run() {
while (true) {
synchronized (str) {
sale();
}
try {
Thread.sleep(100);
} catch (Exception e) {
System.out.println(e.getMessage());
}
if (tickets <= 0) {
break;
}
}
}
public synchronized void sale() {//同步函数
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "is salio" + tickets--);
}
}
}
}
现在还不懂,先放在这里。