public class MyThread extends Thread{ public MyThread(){} public MyThread(String name){ super(name); } @Override public void run(){ for(int i=0;i<100;i++){ System.out.println(getName()+":"+i); } } }
public class MyRunnableDemo{ public static void main(String[] args){ //MyThread my1 = new MyThread(); //MyThread my2 = new MyThread(); MyThread my1 = new MyThread("线程1"); MyThread my2 = new MyThread("线程2"); my1.start(); my2.start(); } }
public class MyRunnable implements Runnable{ @Override public void run(){ for(int i=0;i<100;i++){ System.out.println(Thread.currentThread().getName()+":"+i); } } }
public class MyRunnableDemo{ public static void main(String[] args){ MyRunnable my = new MyRunnable(); //Thread t1 = new Thread(my); //Thread t2 = new Thread(my); Thread t1 = new Thread(my,"线程1"); Thread t2 = new Thread(my,"线程2"); t1.start(); t2.start(); } }
相比继承Thread类,实现Runnable接口的好处
Lock中提供了获取锁和释放锁的方法:
ReentrantLock的构造方法:
public class SellTicket implements Runnable{ private int tickets = 100; //票数 private Lock lock = new ReentrantLock(); @Override public void run(){ while(true){ try{ lock.lock(); if(tickets>0){ try{ Thread.sleep(100); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets+"张票"); tickets--; } }finally{ lock.unlock(); } } } }
public class SellTicketDemo{ public static void main(String[] args){ SellTicket st = new SellTicket(); Thread t1 = new Thread(st,"窗口1"); Thread t2 = new Thread(st,"窗口2"); Thread t3 = new Thread(st,"窗口3"); t1.start(); t2.start(); t3.start(); } }