首页 > 代码库 > 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());            }}