用extend Thread的方法创建线程和用继承runnable接口的方法创建线程,有什么区别呢?
不是特别理解这两种创建方法之间的关联
不是特别理解这两种创建方法之间的关联
2020-07-17
还有一点区别,实现Runnable结构去创建线程类时,可以方便的实现多线程处理类内共享变量。例如:
class MyThread1 implements Runnable{ private int ticketsCont = 5; //共享变量 @Override public void run() { while(ticketsCont > 0) { ticketsCont--; System.out.println(Thread.currentThread().getName() + "买了一张票,剩余票数: " + ticketsCont); } } } public class TicketsRunnable { public static void main(String[] args) { MyThread1 myThread1 = new MyThread1(); Thread t1 = new Thread(myThread1, "A"); Thread t2 = new Thread(myThread1, "B"); Thread t3 = new Thread(myThread1, "C"); t1.start(); t2.start(); t3.start(); } }
举报