java多线程实例
原创
©著作权归作者所有:来自51CTO博客作者李响Superb的原创作品,请联系作者获取转载授权,否则将追究法律责任
package step1;
public class Task {
public static void main(String[] args) throws Exception {
Object A = new Object();
Object B = new Object();
Object C = new Object();
MyThread thread1 = new MyThread("AA",C,A);
MyThread thread2 = new MyThread("BB",A,B);
MyThread thread3 = new MyThread("CC",B,C);
thread1.start();
thread1.sleep(100);
thread2.start();
thread2.sleep(100);
thread3.start();
}
}
class MyThread extends Thread {
String threadName;
private Object pre;
private Object self;
public MyThread(String threadName,Object pre,Object self){
this.threadName = threadName;
this.pre = pre;
this.self = self;
}
public void run() {
int count = 5;
while(count > 0){
synchronized(pre){
synchronized(self){
System.out.println("Java Thread" + this.threadName);
count--;
self.notify();
}
try{
pre.wait();
}catch(Exception e){
}
}
}
System.exit(0);
}
}
package step2;
public class Station extends Thread {
static int tick = 20;
static Object ob = new Object();
public void ticket() {
System.out.println( "卖出了第" + tick + "张票");
tick--;
}
public void run() {
while (tick > 0) {
synchronized (ob) {
if (tick > 0) {
ticket();
}
}
if(tick == 0){
System.out.println("票卖完了");
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
}