package 线程;
public class MyThread extends Thread {
public void run () {
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
}
package 线程;
public class MyThreadDemo {
public static void main(String[] args) {
MyThread m1=new MyThread();
MyThread m2=new MyThread();
//m1.run();
//m2.run();
m1.start();
m2.start();
}
}
package 卖票多线程;
public class SellTicket implements Runnable{
private int ticket=100;
@Override
public void run() {
while(true){
if(ticket>0){
System.out.println(Thread.currentThread().getName()+"正在出售第"+(100-ticket)+"张票");
ticket--;
}
}
}
}
package 卖票多线程;
public class SellTicketDemo {
public static void main(String[] args) {
SellTicket st=new SellTicket();
Thread s1=new Thread(st,"窗口1");
Thread s2=new Thread(st,"窗口2");
Thread s3=new Thread(st,"窗口3");
s1.start();
s2.start();
s3.start();
}
}
package 卖票多线程;
public class SellTicket implements Runnable{
private int ticket=100;
Object obj=new Object();
@Override
public void run() {
while(true){
synchronized (obj){
if(ticket>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName()+"正在出售第"+(100-ticket+1)+"张票");
ticket--;
}
}
}
}
}
package 卖票多线程;
public class SellTicketDemo {
public static void main(String[] args) {
SellTicket st=new SellTicket();
Thread s1=new Thread(st,"窗口1");
Thread s2=new Thread(st,"窗口2");
Thread s3=new Thread(st,"窗口3");
s1.start();
s2.start();
s3.start();
}
}
package 生产者消费者案例;
public class Box {
private Boolean state=false;
private int milk;
public synchronized void put (int milk){
if(state){
try {
wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
this.milk=milk;
System.out.println("送奶工将第"+this.milk+"瓶奶放入奶箱");
state=true;
notifyAll();
}
public synchronized void get(){
if(!state){
try {
wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("用户拿到第"+this.milk+"瓶奶");
state=false;
notifyAll();
}
}
package 生产者消费者案例;
public class Producer implements Runnable{
private Box box;
public Producer (Box box){
this.box=box;
}
@Override
public void run() {
for(int i=1;i<=5;i++){
box.put(i);
}
}
}
package 生产者消费者案例;
public class Customer implements Runnable{
private Box box;
public Customer(Box box) {
this.box=box;
}
public void run(){
while (true){
box.get();
}
}
}
package 生产者消费者案例;
public class BoxDemo {
public static void main(String[] args) {
Box box=new Box();
Producer producer=new Producer(box);
Customer customer=new Customer(box);
Thread t1=new Thread(producer);
Thread t2=new Thread(customer);
t1.start();
t2.start();
}
}
送奶工将第1瓶奶放入奶箱
用户拿到第1瓶奶
送奶工将第2瓶奶放入奶箱
用户拿到第2瓶奶
送奶工将第3瓶奶放入奶箱
用户拿到第3瓶奶
送奶工将第4瓶奶放入奶箱
用户拿到第4瓶奶
送奶工将第5瓶奶放入奶箱
用户拿到第5瓶奶