码迷,mamicode.com
首页 > 编程语言 > 详细

多线程的三种简单表达形式(用卖车票说明)

时间:2017-08-14 20:14:48      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:system   nts   窗口   public   dex   表达   print   try   rgs   

方式1

package example;
public class example11 extends Thread{
static int num=20;
public example11(String name) {
super(name);
}
public void run(){
while(num>0){
synchronized(example11.class){
if(num<1){
break;
}
System.out.println(getName()+"还剩余"+num+"票");
num--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}
}
public static void main(String[] args) {
example11 st=new example11("窗口1");
st.start();
example11 st1=new example11("窗口2");
st1.start();
example11 st2=new example11("窗口3");
st2.start();
}
}

方式2

package example;
public class example12 implements Runnable{
static int num =20;
public void run() {
while(num>0){
synchronized (this) {
if(num<1){
break;
}
System.out.println(Thread.currentThread().getName()+"还剩余"+num+"票");
num--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}
public static void main(String[] args) {
example12 st=new example12();
Thread th1=new Thread(st, "窗口1");
th1.start();
Thread th2=new Thread(st, "窗口2");
th2.start();
Thread th3=new Thread(st, "窗口3");
th3.start();
}
}

方式3

package example;

public class example13 {
static int num = 20;

public static synchronized void tickets() {
if (num >0) {
System.out.println(Thread.currentThread().getName() + "还剩余" + num + "票");
num--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
while (num > 0) {
tickets();
}
}
}, "窗口1").start();
new Thread(new Runnable() {
public void run() {
while (num > 0) {
tickets();
}
}
}, "窗口2").start();
new Thread(new Runnable() {
public void run() {
while (num > 0) {
tickets();
}
}
}, "窗口3").start();
}
}

多线程的三种简单表达形式(用卖车票说明)

标签:system   nts   窗口   public   dex   表达   print   try   rgs   

原文地址:http://www.cnblogs.com/gg128/p/7359563.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!