两个线程同时运行的案例
2014-04-16 15:53
302 查看
/* * 功能:两个线程同时运行的案例 */ package com.test3; public class Demo10_3 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Bird bird=new Bird(10); Pig pig=new Pig(10); Thread t1=new Thread(bird); Thread t2=new Thread(pig); t1.start(); t2.start(); } } //打印 class Pig implements Runnable {int n=0; int times=0; public Pig(int n) { this.n=n; } @Override public void run() { // TODO Auto-generated method stub while (true){ try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } ++times; System.out.println("现在正在打印第"+times+"个hello,world!"); if(times==n) break; } } } //算数学题 class Bird implements Runnable { int n=0;int res=0; int times=0; public Bird(int n) { this.n=n; } @Override public void run() { // TODO Auto-generated method stub while(true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } res+=(++times); System.out.println("当前的结果是"+res); if(times==n) {System.out.println("最后的结果是"+res); break;} } } }
相关文章推荐
- 两个线程同时运行案例
- 两个线程同时运行案例
- 在java中两个线程同时运行是怎么变化的
- 如何让两个线程同时运行
- 懒汉式的安全优化方式,两种方式。线程同时运行的时候,不会创建两个对象
- 有意思 SDWebImage 有两个宏 来判断程序在主线程运行
- 一台机器同时运行两个Tomcat
- 两个相同版本的TomCat同时运行
- 只能在有限的一些情形下使用 volatile 变量替代锁。要使 volatile 变量提供理想的线程安全,必须同时满足下面两个条件:1对变量的写操作不依赖于当前值。 2该变量没有包含在具有其他
- [Linux技巧] 同时运行两个X sessions
- SpringBoot中同时打开运行两个项目,端口占用问题,
- C++ windows多线程 线程描述了进程内代码的执行路径。进程中同时可以有多个线程在执行,为了使他们能够同时运行,操作系统为每个线程轮流分配CPU时间片,为了充分地利用CPU提高软件产品的性能,一
- Java 创建两个线程,和主线程交替运行。
- 同时运行两个TOMCAT的配置
- nginx 同时监听uwsgi服务器两个端口,实现一个服务器运行多个项目
- 一个线程加一运算,一个线程做减一运算,多个线程同时交替运行--synchronized
- 一个函数能否被两个线程同时调用
- 同时运行两个TOMCAT的配置?
- android 同时运行两个ecplise android 项目