创建线程的尝试

来源:互联网 发布:班服t恤淘宝 编辑:程序博客网 时间:2024/06/04 19:54

创建线程三种方法是1.继承Thread类,2.实现Runnable接口,3.使用Executor框架创建线程池,主要实现前两个经常用到的方法。
1:继承Thread

public class ThreadDemo1 extends Thread{    public int ticket=5;    public ThreadDemo1(String name){        super(name);    }    public void run() {        for (;ticket>0;ticket--) {            System.out.println(Thread.currentThread().getName()+"Ticket:"+ticket);        }    }    public static void main(String[] args){        new ThreadDemo1("线程A").start();        new ThreadDemo1("线程B").start();    }}

重写继承下来的run方法即可,输出:

线程ATicket:5线程BTicket:5线程ATicket:4线程BTicket:4线程ATicket:3线程ATicket:2线程ATicket:1线程BTicket:3线程BTicket:2线程BTicket:1

2.实现Runnable接口

public class ThreadDemo2 implements Runnable{    public int ticket=5;    public void run() {        synchronized(this){            for (;ticket>0;ticket--) {                System.out.println(Thread.currentThread().getName()+"Ticket:"+ticket);            }        }    }    public static void main(String[] args) {        ThreadDemo2 td2=new ThreadDemo2();        new Thread(td2,"线程A").start();        new Thread(td2,"线程B").start();    }}

实现Runnable接口也是要实现run方法,但是这种方式可以共享一个变量,输出:

线程ATicket:5线程ATicket:4线程ATicket:3线程ATicket:2线程ATicket:1
0 0
原创粉丝点击