匿名内部类实现多线程
JAVA多线程实现方式主要有三种:继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。
package com.zyw.perform.test;
import com.zyw.perform.PerformApplication;
import org.springframework.boot.SpringApplication;
/**
* @author zyw
*/
public class Demo {
/**
* 匿名内部类写法
* 匿名内部类也就是没有名字的内部类
正因为没有名字,所以匿名内部类只能使用一次,它通常用来简化代码编写
但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口
*/
public void SEND(){
System.out.println("模拟接收到了数据11111111111111111");
show();
System.out.println("新增这个数据到库里面");
System.out.println("反馈新增成功");
}
public void show(){
Thread thread = new Thread(new Runnable() {
private int ticket = 1000;
@Override
public void run() {
// System.out.println("接收数据传入到其他系统 通过mq形式");
for (int i = 0; i < 1000; i++) {
if (this.ticket > 0) {
synchronized (this){//修改地方加锁
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " 卖票:ticket " + this.ticket--);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
});
Thread thread1414 = new Thread(thread);
Thread thread1415 = new Thread(thread);
thread1414.start();
thread1415.start();
}
public static void main(String[] args) {
Demo demo = new Demo();
demo.SEND();
}
}