Java多线程是指在一个Java程序中同时执行多个线程,每个线程独立执行自己的任务。多线程编程可以提高程序的并发性能和响应能力。在Java中,多线程编程主要依赖于Thread类和Runnable接口。
创建线程
Java中创建线程的常见方式有两种:继承Thread类和实现Runnable接口。
public class MyThread extends Thread {
@Override
public void run() {
// 内容
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
// 内容
}
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
总结:
实现Runnable接口比继承Thread类所具有的优势:
1):适合多个相同的程序代码的线程去处理同一个资源
2):可以避免java中的单继承的限制
3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立
4):线程池只能放入实现Runable类线程,不能直接放入继承Thread的类
线程对象的生命周期![](https://img-blog.csdnimg.cn/ae7f3353d6934387992af0333d2c644b.png)
运用多线程实现卖票功能
public class Tickets {
private int num;
public Tickets(){};
public Tickets(int num){
this.num=num;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
public class Operate {
private Tickets tickets;
public Operate(Tickets tickets){
this.tickets=tickets;
}
public void sale(){
synchronized (this){
if(tickets.getNum()>0){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if(tickets.getNum()>0){
int num=tickets.getNum();
System.out.println(Thread.currentThread().getName()+"正在卖票:"+tickets.getNum()+"售票剩余"+num);
--num;
tickets.setNum(num);
}
}
}
}
}
public class Service
{
public static void main(String [] args)
{
Tickets tickets=new Tickets(100);
Operate operate=new Operate(tickets);
new Thread(()->{
while(tickets.getNum()>0) operate.sale();
},"窗口1").start();
new Thread(()->{
while(tickets.getNum()>0) operate.sale();
},"窗口2").start();
new Thread(()->{
while(tickets.getNum()>0) operate.sale();
},"窗口3").start();
new Thread(()->{
while(tickets.getNum()>0) operate.sale();
},"窗口4").start();
}
}
以下是部分运行结果: