您的位置:首页 > 其它

多线程的应用

2015-08-04 19:02 288 查看
public class MyRunable implements Runnable {

private int i = 100;

private String s = “abs”;

@Override
public void run() {
while (i > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {

e.printStackTrace();
}
synchronized (s) {
if(i>0){
System.out.println(Thread.currentThread().getName() + "卖出了第" + i + "张票");
i--;
}

}
}

}


//这个和上个程序是独立的

public class MyThread extends Thread {

private int ticket = 200;

private String s = “abc”;

public MyThread() {

}

// 构造方法
public MyThread(String name) {
super(name);
}

public void run() {
while (ticket > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {

e.printStackTrace();
synchronized (s) {
if (ticket > 0) {
System.out.println(getName() + "卖出了第" + ticket + "张票");
ticket--;
}

}
}
}
}


public class Test {

public static void main(String[] args) {
// MyThread t1=new MyThread("甲");
// MyThread t2=new MyThread("乙");
// MyThread t3=new MyThread("丙");
// MyThread t4=new MyThread("丁");
// t1.start();
// t2.start();
// t3.start();
// t4.start();
MyRunable runnable = new MyRunable();
Thread t1 = new Thread(runnable, "甲");
Thread t2 = new Thread(runnable, "乙");
Thread t3 = new Thread(runnable, "丙");
Thread t4 = new Thread(runnable, "丁");
t1.start();
try {
t1.join(1000);//等待t1运行1秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t2.start();
t3.start();
t4.start();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: