在Java中常用的实现多线程的两种方式是使用Thread类或者实现Runnable接口。
Runnable示例代码:实现Runnable接口,再通过Thread的构造函数创建线程。
Runnable是一个接口,并且只包含了一个run()方法。
基于Java8的Runnable源码:
- @FunctionalInterface
- public interface Runnable {
- /**
- * When an object implementing interface <code>Runnable</code> is used
- * to create a thread, starting the thread causes the object's
- * <code>run</code> method to be called in that separately executing
- * thread.
- * <p>
- * The general contract of the method <code>run</code> is that it may
- * take any action whatsoever.
- *
- * @see java.lang.Thread#run()
- */
- public abstract void run();
- }
- public class MyThread implements Runnable{
- private int ticket=10;
- public void run() {
- // TODO 自动生成的方法存根
- for(int i=0;i<20;i++)
- {
- if(this.ticket>0)
- {
- System.out.println(Thread.currentThread().getName()+" 卖票:ticket"+this.ticket--);
- }
- }
- }
- }
- public class Hello {
- public static void main(String [] agrs)
- {
- MyThread myThread=new MyThread();
- Thread t1=new Thread(myThread);
- Thread t2=new Thread(myThread);
- Thread t3=new Thread(myThread);
- t1.start();
- t2.start();
- t3.start();
- }
- }
结果:
Thread-0 卖票:ticket10
Thread-2 卖票:ticket10
Thread-1 卖票:ticket10
Thread本身是一个类,然后它实现了Runnable接口,因此在使用Thread时我们只需要继承Thread并重写它的run()方法就好。
Thread示例:
- public class NewThread extends Thread{
- private int ticket=10;
- public void run()
- {
- for(int i=0;i<20;i++)
- {
- if(this.ticket>0)
- {
- System.out.println(this.getName()+" 卖票:ticket"+this.ticket--);
- }
- }
- }
- }
- public class Hello {
- public static void main(String [] agrs)
- {
- NewThread t1=new NewThread();
- NewThread t2=new NewThread();
- NewThread t3=new NewThread();
- t1.start();
- t2.start();
- t3.start();
- }
- }
运行结果:
Thread-0 卖票:ticket10
Thread-0 卖票:ticket9
Thread-0 卖票:ticket8
Thread-0 卖票:ticket7
Thread-0 卖票:ticket6
Thread-0 卖票:ticket5
Thread-0 卖票:ticket4
Thread-0 卖票:ticket3
Thread-0 卖票:ticket2
Thread-2 卖票:ticket10
Thread-2 卖票:ticket9
Thread-2 卖票:ticket8
Thread-2 卖票:ticket7
Thread-2 卖票:ticket6
Thread-2 卖票:ticket5
Thread-2 卖票:ticket4
Thread-2 卖票:ticket3
Thread-2 卖票:ticket2
Thread-2 卖票:ticket1
Thread-1 卖票:ticket10
Thread-1 卖票:ticket9
Thread-1 卖票:ticket8
Thread-1 卖票:ticket7
Thread-1 卖票:ticket6
Thread-1 卖票:ticket5
Thread-1 卖票:ticket4
Thread-1 卖票:ticket3
Thread-1 卖票:ticket2
Thread-1 卖票:ticket1
Thread-0 卖票:ticket1