一、线程同步
代码块:
代码如下(示例):
package demo01;
public class Demo05Ticket {
public static void main(String[] args) {
RunnableImpl run= new RunnableImpl();
Thread t0= new Thread(run);
Thread t1= new Thread(run);
Thread t2= new Thread(run);
t0.start();
t1.start();
t2.start();
}
}
二、生产、消费者
代码如下(示例):
package demo03;
public class demo03WatiAndNotify {
public static void main(String[] args) {
Object obj= new Object();
//创建第一个消费者
new Thread() {
public void run() {
while(true) {
synchronized(obj) {
System.out.println(“消费:1:告知老板要的包子的种类”);
try {
obj.wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费者2:包子已经做好了,开吃");
System.out.println("======================");
}
}
}
}.start();
new Thread() {
public void run() {
while(true) {
try {
Thread.sleep(2000);
}catch(InterruptedException e) {
e.printStackTrace();
}
synchronized (obj) {
System.out.println("生产者:老板花2秒做好了一个包子,告知顾客吃包子");
obj.notify();
}
}
}
}.start();
}
}