首页 > 代码库 > java多线程基础知识
java多线程基础知识
1.ThrTest.java 继承Thread类方式
public class ThrTest extends Thread { private String name; public ThrTest() { } public ThrTest(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "运行 " + i); } } public static void main(String[] args) { ThrTest h1=new ThrTest("A"); ThrTest h2=new ThrTest("B");// h1.run();// h2.run(); h1.start(); h2.start(); }}
2.RunnTest.java实现Runnable接口方式
public class RunnTest implements Runnable { private String name; public RunnTest() { } public RunnTest(String name) { this.name = name; } private int ticket = 5; //5张票 public void run() { for (int i=0; i<=20; i++) { if (this.ticket > 0) { System.out.println(this.name + Thread.currentThread().getName()+ "正在卖票"+this.ticket--); } } } public static void main(String[] args) { RunnTest h1=new RunnTest("线程A"); //资源共享 // Thread demo= new Thread(h1,"1号窗口");// Thread demo1=new Thread(h1,"2号窗口");// Thread demo2=new Thread(h1,"3号窗口"); Thread demo= new Thread(h1); Thread demo1=new Thread(h1); Thread demo2=new Thread(h1); demo.start(); demo1.start(); System.out.println("线程启动之前---》" + demo2.isAlive()); demo2.start(); System.out.println("线程启动之后---》" + demo2.isAlive()); }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。