实现多线程

来源:互联网 发布:淘宝抽奖活动是真的吗 编辑:程序博客网 时间:2024/06/03 03:24
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;}}}
}


 

 

 

 

0 0
原创粉丝点击