多线程售票示例
package *; class Ticket implements Runnable{ static int number=20;//买票 @Override public void run() { synchronized(this){//代码块:同步块,加锁,控制线程顺序 System.out.println("开始"); System.out.println(Thread.currentThread().getName()+"买了第"+number+"张票"); number--; System.out.println("结束"); } } } class Ticket2 implements Runnable{ static int number=30; @Override public void run() { // TODO Auto-generated method stub System.out.println("开始"); System.out.println(Thread.currentThread().getName()+"买了第"+number+"张票"); number--; System.out.println("结束"); } } public class Er { public static void main(String[] args) { Ticket ticket=new Ticket(); new Thread(ticket,"t1").start(); new Thread(ticket,"t2").start(); new Thread(ticket,"t3").start(); new Thread(ticket,"t4").start(); new Thread(ticket,"t5").start(); new Thread(ticket,"t6").start(); Ticket2 ticket2=new Ticket2(); new Thread(ticket2,"t1").start(); new Thread(ticket2,"t2").start(); new Thread(ticket2,"t3").start(); } }
多线程示例
oraclepeixun