看不懂拉到最后有解释
1.继承Thread类,重写run方法
public class ExtendThread extends Thread{
static int times = 100;
static Object key = "aa";//值是任意的
public ExtendThread(String name){
super(name);
}
@Override
public void run() {
while (times>0) {
// synchronized (key) {
if (times > 0) {
System.out.println(getName()+"卖出了第"+times+"张票");
times--;
} else {
System.out.println("无票了");
}
}
// }
}
public static void main(String[] args) {
ExtendThread extendThread1 = new ExtendThread("窗口1");
ExtendThread extendThread2 = new ExtendThread("窗口2");
ExtendThread extendThread3 = new ExtendThread("窗口3");
extendThread1.start();
extendThread2.start();
extendThread3.start();
}
}
2.实现Runnable接口,重写run方法
public class RunnableThread implements Runnable{
private int times = 30; // static int times = 30;
static Object key = "123";
@Override
public void run() {
while (times>0){
synchronized (key) {
if (times > 0) {
System.out.println(Thread.currentThread().getName()+"卖出了第"+times+"张票");
times--;
}else {
System.out.println("无票了哈哈");
}
}
}
}
public static void main(String[] args) { // Runnable runnableThread = new RunnableThread();
RunnableThread runnableThread = new RunnableThread();
new Thread(runnableThread).start();
new Thread(runnableThread).start();
new Thread(runnableThread).start();
} }
//解释
public class test extends Thread{
// 为了保持票数的一致,票数要静态
static int tick = 20;
// 通过构造方法给线程名字赋值
public test(String name) {
super(name);// 给线程名字赋值
}
// 创建一个静态钥匙
static Object ob = "aa";//值是任意的
// 重写run方法,实现买票操作
@Override
public void run() {
while (tick > 0) {
synchronized (ob) {// 这个很重要,必须使用一个锁,
// 进去的人会把钥匙拿在手上,出来后才把钥匙拿让出来
if (tick > 0) {
System.out.println(getName() + "卖出了第" + tick + "张票");
tick--;
} else {
System.out.println("票卖完了");
}
}
// try {
// sleep(1000);//休息一秒
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
public static void main(String[] args) {
test test1 = new test("窗口1");
test test2 = new test("窗口2");
test test3 = new test("窗口3");
test1.start();
test2.start();
test3.start();
}
}