文章目录
前面所讲的如何创建一个线程,即通过继承Thread类或实现Runnable接口创建一个线程,通过start方法调用run方法,run方法工作,线程run结束后,线程退出。
这种执行模式是一种粗粒度的执行模式,再这样的执行过程中,子线程与子线程之间、和main线程之间缺乏交流。我们希望,在线程与线程之间有信息交流通讯,这样就属于一种细粒度的编程模式。
在Java里面一般是通过共享变量达到信息共享。
一,共享变量的两种方式
1,static 变量
package com.antique;
public class Main {
public static void main(String[] args) throws InterruptedException {
new TestThread().start();
new TestThread().start();
new TestThread().start();
new TestThread().start();
}
}
class TestThread extends Thread {
// private int tickets = 100; 每个线程都有100张门票,没有共享
private static int tickets = 100; // static变量是共享的,所有的线程共享
@Override
public void run() {
while (true) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + " is selling tickets " + tickets);
tickets--;
} else {
break;
}
}
}
}
运行结果如图: