首页 文章 精选 留言 我的

精选列表

搜索[java脚本],共10000篇文章
优秀的个人博客,低调大师

Java 学习(28)---(线程的控制 / 生命周期 /解决安全问题)

线程的控制 休眠线程 public class ThreadSleep extends Thread { @Override publicvoid run() { for ( int x = 0; x < 100; x++) { System. out .println(getName() + ":" + x + ", 日 期 : " + newDate()); // 睡眠 // 困了,我稍微休息 1 秒钟try { Thread. sleep (1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } 加入线程 publicclass ThreadJoin extends Thread { @Override publicvoid run() { for ( int x = 0; x < 100; x++) { System. out .println(getName() + ":" + x); } } } ThreadJoin tj1 = new ThreadJoin(); ThreadJoin tj2 = new ThreadJoin(); ThreadJoin tj3 = new ThreadJoin(); tj1.setName(" 李渊 " ); tj2.setName(" 李世民 " ); tj3.setName(" 李元霸 " ); tj1.start(); try { // 李渊执行完,再执行其他两个 tj1.join(); } catch (InterruptedException e) { e.printStackTrace(); } tj2.start(); tj3.start(); 礼让线程 publicclass ThreadYield extends Thread { @Override publicvoid run() { for (int x = 0; x < 100; x++) { System. out .println(getName() + ":" + x); // 让其他线程先走 Thread. yield (); } } } 后台线程 ThreadDaemon td1 = new ThreadDaemon(); ThreadDaemon td2 = new ThreadDaemon(); td1.setName(" 关羽 " ); td2.setName(" 张飞 " ); // 设置守护线程,主线程结束后,守护线程也会结束 td1.setDaemon(true); td2.setDaemon(true); td1.start(); td2.start(); // 设 置 主 线 程 名 为 “ 刘 备 ” Thread.currentThread().setName(" 刘备 " ); for ( int x = 0; x < 5; x++) { System.out.println(Thread.currentThread().getName() + ":" + x); } 终止线程 public class ThreadStop extends Thread { @Override public void run() { System. out.println(" 开始执行: " +new Date()); // 我要休息 10 秒钟,亲,不要打扰我哦 try { Thread.sleep(10000); }catch(Interrupted Exception e) { // e.printStackTrace(); System.out.println( " 线程被终止了" ); } System. out .println(" 结束执行: " +new Date()); } } ThreadStop ts =new ThreadStop(); ts.start(); // 你超过三秒不醒过来,我就干死你 try { Thread.sleep(3000); // ts.stop(); ts.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } 线程的生命周期 多线程安全问题 判断一个程序是否有线程安全问题的依据 ) A:是否有多线程环境 B:是否有共享数据 C:是否有多条语句操作共享数据 同步解决线程安全问题 同步代码块 synchronized( 对象 ) { 需要被同步的代码 ; } 这里的锁对象可以是任意对象。 synchronized(d) { if(tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " 正在出售第 " + (tickets--) + " 张 票 " ); } } 同步方法 把同步加在方法上。这里的锁对象是 this privatesynchronizedvoid sellTicket() { if(tickets > 0) { try { Thread.sleep(100); } catch(InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() +" 正在出售第 " + (tickets--) + " 张 票 " ); } } 静态同步方法 把同步加在方法上。 这里的锁对象是当前类的字节码文件对象(反射再讲字节码文件对象) private static synchronized void sellTicket() { if (tickets > 0) { try { Thread.sleep(100); } catch(InterruptedException e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " 正在出售第 " + (tickets--) +" 张票 " ); } } 同步锁对象 // 定义票 private int tickets = 100; // 定义锁对象 private Lock lock =new ReentrantLock(); @Override public void run() { while (true) { try{ // 加锁 lock.lock(); if (tickets > 0) { try { Thread.sleep(100); } catch(InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " 正在出售第 " + (tickets--) +" 张票 " ); } }finally{ // 释放锁 lock.unlock(); } } } 同步的好处 同步的出现解决了多线程的安全问题。 同步的弊端 当线程相当多时,因为每个线程都会去判断同步上的锁,这是很耗费资源的,无形中会降低程序的运行效率。

优秀的个人博客,低调大师

Java多线程进一步的理解之------------线程池

public class ThreadPoolTest { public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 1; i <=10 ; i++) { final int task = i; executorService.execute(new Runnable() { @Override public void run() { for (int j = 1; j <= 10; j++) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " is for " + " j= " + j +" task = " + task); } } }); } //executorService.shutdown(); } } 代码很简单就不解释了 看一下第二种方式 public class SemaphoreTest { public static void main(String[] args) { ExecutorService service = Executors.newCachedThreadPool(); final Semaphore s = new Semaphore(3); for (int i = 0; i < 10; i++) {// 开是个对象 Runnable runnable = new Runnable() { @Override public void run() { try { s.acquire();// 判断对象的信号灯,亮就代表有线程 }catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程" + Thread.currentThread() + "进入,当前已有" + s.availablePermits()); try { Thread.sleep((long)(Math.random()*10000)); }catch (InterruptedException e){ e.printStackTrace(); } System.out.println("线程"+Thread.currentThread()+"即将离开"); s.release(); System.out.println("线程"+Thread.currentThread()+"线程已离开,当前已有"+s.availablePermits()); } }; service.execute(runnable);// 把对象装线程池 } } }

优秀的个人博客,低调大师

Java多线程进一步的理解之------------缓存机制

public class CacheDemo { private Map<String,Object> cache = new HashMap<String,Object>(50); public static void main(String[] args) { } /* * 多个线程的并发执行,保证数据正确 * */ private ReadWriteLock rwl = new ReentrantReadWriteLock(); public Object getData(String key) { rwl.readLock().lock();// 加读锁,都可以读, Object value = null; try{ value = cache.get(key); if (value == null) { rwl.readLock().unlock(); // 释放读锁,都不可以读,让第一个线程去数据库中查数据,查好后输出, rwl.writeLock().lock(); // 加写锁,只有第一个线程可以加写锁添加成功, try { if (value == null) { // 保证不让后来的线程去加写锁 value = "aaaa";// 这是从数据库中取得值 } }finally { rwl.writeLock().unlock(); // 第一个线程释放写锁 } rwl.readLock().lock(); // 进而去读。其他线程开始加写锁,最后也会被释放 } }finally { rwl.readLock().unlock(); } return value; } } 要实现一个缓存并不是那么容易的,要考虑很多种情况

优秀的个人博客,低调大师

Java多线程进一步的理解------------实现读写锁

public class ReadAndWriteLock { public static void main(String[] args) { final QueueJ q = new QueueJ(); for (int i = 0; i <3 ; i++) { new Thread(){ @Override public void run() { while (true) { q.get(); } } }.start(); new Thread(){ @Override public void run() { q.put(new Random().nextInt(1000)); } }.start(); } } } class QueueJ { private Object data = null;//共享数据,只能有一个线程 private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); public void get() { rwl.readLock().lock(); try { System.out.println(Thread.currentThread().getName() + "will read"); Thread.sleep((long)(Math.random()*1000)); System.out.println(Thread.currentThread().getName() + "have read"); }catch (InterruptedException e) { e.printStackTrace(); }finally { rwl.readLock().unlock(); } } public void put(Object data) { rwl.writeLock().lock(); try { System.out.println(Thread.currentThread().getName() + "will write"); Thread.sleep((long)(Math.random()*1000)); this.data = data; System.out.println(Thread.currentThread().getName() + "have write"); }catch (InterruptedException e){ e.printStackTrace(); }finally { rwl.writeLock().unlock(); } } } 读之前,加上读锁,写之前加上写锁

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码