public ProducerThread(PublicResource resource) {
this.resource = resource;
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
resource.increace();
}
}
}
/**
* 消费者线程,负责消费公共资源
*/
public class ConsumerThread implements Runnable {
private PublicResource resource;
public ConsumerThread(PublicResource resource) {
this.resource = resource;
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
resource.decreace();
}
}
}
public class ProducerConsumerTest {
public static void main(String[] args) {
PublicResource resource = new PublicResource();
new Thread(new ProducerThread(resource)).start();
new Thread(new ConsumerThread(resource)).start();
new Thread(new ProducerThread(resource)).start();
new Thread(new ConsumerThread(resource)).start();
new Thread(new ProducerThread(resource)).start();
new Thread(new ConsumerThread(resource)).start();
}
} 作者: lucy198921 时间: 2013-3-24 15:55
多线程的同步控制与线程间的通信:可以用synchronized、wait()和notifyAll()完成以下情景
模拟3个人排队买票,每人买一张票。售票员(TicketSeller类)只有1张5元的钱,电影票5元一张。
张某拿着1张20元的人民币排在第一,李某拿着1张10元的人民币排在第二,王某拿着1张5元的人民币排在第三。
(提示:定义一个售票员TicketSeller类,属性包括5元钱张数fiveNumber、10元钱张数tenNumber和20元钱张数twentyNumber,方法为同步方法卖票sellTicket(int receiveMoney), 创建三个线程张某Zhang、李某Li和王某Wang,这三个线程共享一个售票员类对象。)
class MyThread88 implements Runnable {
int i=100;
public synchronized void m1() throws InterruptedException {
i=1000;
Thread.sleep(5000);
System.out.println("i"+"="+i);
}
public synchronized void m2() throws InterruptedException {
Thread.sleep(2500);
i=2000;
}
public void run() {
try {
m1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class TongBu {
public static void main(String[] args) {
MyThread88 k = new MyThread88();
Thread t = new Thread(k);
t.start();
try {
k.m2();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(k.i);
}
}