1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > java多线程实现卖火车票小案例同步代码块优先级守护线程

java多线程实现卖火车票小案例同步代码块优先级守护线程

时间:2022-01-24 23:24:09

相关推荐

java多线程实现卖火车票小案例同步代码块优先级守护线程

/***

*

* @author 时光机jay

* @version 1.8

* @since /9/28

*

* */

public class Test33 {

static int a = 100;

public static void main(String[] args) {

// 内部类实现 Runnable 可以多个线程调用

Runnable th = new Runnable() {

@Override

public void run() {

while (true) {

// 同步代码块保证安全

synchronized(this) {

if (a <= 0) {

break;

}

System.out.println(Thread.currentThread().getName()+"卖第" + (a--) + "张票");

}

}

}

};

// 传入 Runnable对象创建Thread线程

Thread th1 = new Thread(th,"甲");

Thread th2 = new Thread(th,"乙");

Thread th3 = new Thread(th,"丙");

// 设置优先级

th1.setPriority(Thread.MAX_PRIORITY);

th2.setPriority(Thread.MIN_PRIORITY);

th3.setPriority(Thread.NORM_PRIORITY);

// 设置丙保护线程

th3.setDaemon(true);

// boolean daemon = th1.isDaemon();

// System.out.println(daemon);

th1.start();

th2.start();

th3.start();

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。