实现多线程方法1:继承Thread类完整代码
//示例: 售卖100张门票,实现多个窗口售卖 //创建多线程方法1: //1.继承Thread 多线程类 class Ticket extends Thread { // 共有100张门票 private int ticketNum = 100; // 2.重写run()方法 @Override public void run() { // 3.线程执行的操作,声明在run中 while (true) { if (ticketNum > 0) { System.out.println(Thread.currentThread().getName() + "售卖的门票号:" + ticketNum); ticketNum--; }else return; } } public static void main(String[] args) { // 4.创建Thread 子类对象 Ticket thread1 = new Ticket(); thread1.setName("窗口1"); // 5.调用start()启动线程 thread1.start(); Ticket thread2 = new Ticket(); thread2.setName("窗口2"); thread2.start(); Ticket thread3 = new Ticket(); thread3.setName("窗口3"); thread3.start(); } }
实现多线程方法2:匿名子类
//示例: 售卖100张门票,实现多个窗口售卖 class Ticket extends Thread { // 共有100张门票 :为了方便调用声明为静态 public static int ticketNum = 100; public static void main(String[] args) { new Thread(){ // 2.重写run()方法 @Override public void run() { //3.线程执行的操作,声明在run中 while (true) { if (ticketNum > 0) { System.out.println(Thread.currentThread().getName() + "售卖的门票号:" + ticketNum); ticketNum--; }else return; } } }.start(); new Thread(){ // 2.重写run()方法 @Override public void run() { //3.线程执行的操作,声明在run中 while (true) { if (ticketNum > 0) { System.out.println(Thread.currentThread().getName() + "售卖的门票号:" + ticketNum); ticketNum--; }else return; } } }.start(); } }
实现多线程创建:方法三:实现Runnab接口,重写run方法
//示例: 售卖100张门票,实现多个窗口售卖 // 1.实现Runna接口 class Ticket implements Runnable { // 共有100张门票 private static int ticketNum = 100; //2.重写run()方法 @Override public void run() { // 3.线程执行的操作,声明在run中 while (true) { if (ticketNum > 0) { System.out.println(Thread.currentThread().getName() + "售卖的门票号:" + ticketNum); ticketNum--; }else return; } } public static void main(String[] args) { // 4.创建实现类对象 Ticket thread = new Ticket(); // 5.将实例对象作为参数传递到构造器中,创建Thread对象 Thread t1 = new Thread(thread); t1.start(); Thread t2 = new Thread(thread); t1.start(); Thread t3 = new Thread(thread); t1.start(); }
两种实现多线程方式比较:
开发中,优先使用实现Runnable接口的方式。
1.实现接口没有类的单继承的局限性;
2.实现接口更加适合处理多个数据共享的情况;