实现多线程

public class test {
	public static void main(String[] args) throws InterruptedException {
		MutliThread m = new MutliThread();
		Thread t1 = new Thread(m, "Window 1");
		Thread t2 = new Thread(m, "Window 2");
		t1.start();
		try {
			Thread.sleep(10);
		} catch (Exception e) {
			// TODO: handle exception
		}
		m.flag = false;
		t2.start();
	}
}

class MutliThread implements Runnable {
	private static int ticket = 100;// 每个线程都拥有100张票
	boolean flag = true;

	public void run() {
		if (flag) {
			while (true) {
				synchronized (MutliThread.class) {
					if (ticket > 0) {
						try {
							Thread.sleep(10);
						} catch (Exception e) {
						}
						System.out.println(ticket-- + " is saled by "
								+ Thread.currentThread().getName());
					} else {
						break;
					}
				}
			}
		} else {
			while (true) {
				synchronized (MutliThread.class) {
					if (ticket > 0) {
						show();
					} else {
						break;
					}
				}
			}
		}
	}

	public static synchronized void show() {
		try {
			Thread.sleep(15);
		} catch (Exception e) {
		}
		System.out.println(Thread.currentThread().getName()
				+ "show============> :" + ticket--);
	}
}


 

2.继承 Thread 方法

 

public class test {
	public static void main(String[] args) throws InterruptedException {
		MutliThread m = new MutliThread();
		Thread t1 = new Thread(m, "Window 1");
		Thread t2 = new Thread(m, "Window 2");
		Thread t3 = new Thread(m, "Window 3");
		t2.start();
		t1.start();
		t3.start();
	}
}

class MutliThread extends Thread {
	private int ticket = 10;// 每个线程都拥有100张票

	public void run() {
		while (true) {
			if (ticket > 0) {
				System.out.println(ticket-- + " is saled by "
						+ Thread.currentThread().getName());
			} else {
				break;
			}
		}
	}
}


 

 

 

 

你可能感兴趣的:(多线程,线程)