标签:override -- java over 输出 zed sso dex ring
如果一个类继承Thread,则不适合资源共享。但是如果实现了Runable接口的话,则很容易的实现资源共享。
1.继承Thread——多线程执行各自的资源,线程执行的资源互不干涉,各自执行各自的
package TestThread; public class TicketsThread { public static void main(String[] args) { Tickets tickets1 = new Tickets(); tickets1.start(); Tickets tickets2 = new Tickets(); tickets2.start(); } } class Tickets extends Thread{ private int num=10; @Override public void run() { while(num>0){ sale(); } } synchronized void sale() { if(num > 0){ System.out.println(Thread.currentThread().getName() + "卖出一张票,还剩余"+ (--num) + "张票。"); try{ Thread.sleep(100); }catch(InterruptedException e){ e.printStackTrace(); } } } }
控制台输出(各自操作各自的10张票,互不干涉):
2.实现Runnable接口——多线程共享同一资源:
package TestThread; public class TicketsThread { public static void main(String[] args) { Tickets tickets = new Tickets(); new Thread(tickets).start(); new Thread(tickets).start(); } } class Tickets extends Thread{ private int num=10; @Override public void run() { while(num>0){ sale(); } } synchronized void sale() { if(num > 0){ System.out.println(Thread.currentThread().getName() + "卖出一张票,还剩余"+ (--num) + "张票。"); try{ Thread.sleep(100); }catch(InterruptedException e){ e.printStackTrace(); } } } }
控制台输出(两个线程操作共同的10张票,按照顺序依次递减):
转自:https://blog.csdn.net/qq_37791764/article/details/77752363
java多线程:继承Thread和实现Runable接口的区别
标签:override -- java over 输出 zed sso dex ring
原文地址:https://www.cnblogs.com/vickylinj/p/10923491.html