博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 多线程(一)
阅读量:2344 次
发布时间:2019-05-10

本文共 2062 字,大约阅读时间需要 6 分钟。

public class Test1Thread extends Thread {
private int ticketscount = 100; @Override public void run() { while (true) { sale(); } } //lock private synchronized void sale(){ if (ticketscount > 0) { try { //sleep Thread.sleep(1000); //wakeup //Thread.interrupted(); } catch (Exception e) { e.printStackTrace(); } int curent = ticketscount--; System.out.println(String.format("%s卖出了第%s张票", Thread.currentThread().getName(), curent)); } }}
public class TestRunable implements Runnable {
private int ticketscount = 100; private Lock lock = new ReentrantLock(); @Override public void run() { while (true){ sale(); } } private void sale(){ try { lock.lock(); if(ticketscount>0){ Thread.sleep(1000); System.out.println(String.format("%s卖出了第%s张票", Thread.currentThread().getName(),ticketscount--)); } }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } }}
public class TestMain {
/** * 对于java程序,只要有一个前台线程在运行,这个进程就不会结束 * 如果只有后台线程运行,进程会结束 */ public static void test1(){ //创建一个资源对象 Test1Thread test1Thread = new Test1Thread(); //创建多个线程来竞争资源 //线程一 Thread thread1 = new Thread(test1Thread); thread1.setName("John"); //前台线程 thread1.setDaemon(false); thread1.start(); //线程二 Thread thread2 = new Thread(test1Thread); //前台线程 thread2.setDaemon(false); thread2.setName("BOB"); thread2.start(); } public static void test2(){ TestRunable runable = new TestRunable(); new Thread(runable).start(); new Thread(runable).start(); } public static void main(String[] args){ // test1(); test2(); }}

转载地址:http://zqnvb.baihongyu.com/

你可能感兴趣的文章
Hive 数据库仓库的基本操作
查看>>
elasticsearch和logstash和kibana
查看>>
自动化运维工具ansible安装及使用
查看>>
seq妙用一则
查看>>
HAProxy安装和配置大全
查看>>
mysql的数据备份及恢复
查看>>
pip安装使用详解
查看>>
python中的urllib模块中的方法
查看>>
LAMP快速安装
查看>>
python常用模块
查看>>
sql去除重复语句
查看>>
OpenStack安装部署
查看>>
mysql字符集乱码问题
查看>>
python读写文件file写入到mysql
查看>>
saltstack 数据系统——Grains和pillar
查看>>
postgresql - 三种安装方式
查看>>
Web服务器之Nginx详解(理论部分)
查看>>
Web服务器之Nginx详解(操作部分)
查看>>
CentOS6.4+Nginx1.4.2+MySQL5.6.13+PHP5.5.3+xCache3.03(最新LNMP编译安装过程)
查看>>
Linux下的qperf测量网络带宽和延迟和iptraf网卡流量监控
查看>>