java线程——模拟烧水,洗茶杯与泡茶过程
2016-08-27 20:45
483 查看
在日常生活中,我们喝茶之前,必须完成完成烧开水,清洗茶杯,以及泡茶过程才能喝到清香的茶水。如果一项项的去完成的话,就会浪费很多时间。我们知道,在烧水的过程中,我们完全可以一边清洗茶杯,这样就能节约更多的时间了。那么我们如何利用程序来模拟实现这一过程呢?
public class Test{
public static void main(String[] args) {
MyRunnable3 myRunnable3=new MyRunnable3();
MyRunnable4 myRunnable4=new MyRunnable4();
Thread t1=new Thread (myRunnable3);
Thread t2=new Thread (myRunnable4);
t1.setName("烧水");
t2.setName("洗杯子");
t1.start();
t2.start();
try {
t1.join();
} catch (InterruptedException e) {
//等待烧水完成
e.printStackTrace();
}
try {
t2.join();
} catch (InterruptedException e) {
// 等待洗杯子完成
e.printStackTrace();
}
System.out.println("泡茶....");
}
}
class MyRunnable3 implements Runnable{
public void run(){
System.out.println("烧开水去....");
try {
Thread.sleep(5000); //每运行一次,休眠一秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("烧完了.......");
}
}
class MyRunnable4 implements Runnable{
public void run(){
for(int i=1;i<10;i++){
System.out.println("洗 "+i+"杯子去....");
try {
Thread.sleep(1000); //每运行一次,休眠一秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test{
public static void main(String[] args) {
MyRunnable3 myRunnable3=new MyRunnable3();
MyRunnable4 myRunnable4=new MyRunnable4();
Thread t1=new Thread (myRunnable3);
Thread t2=new Thread (myRunnable4);
t1.setName("烧水");
t2.setName("洗杯子");
t1.start();
t2.start();
try {
t1.join();
} catch (InterruptedException e) {
//等待烧水完成
e.printStackTrace();
}
try {
t2.join();
} catch (InterruptedException e) {
// 等待洗杯子完成
e.printStackTrace();
}
System.out.println("泡茶....");
}
}
class MyRunnable3 implements Runnable{
public void run(){
System.out.println("烧开水去....");
try {
Thread.sleep(5000); //每运行一次,休眠一秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("烧完了.......");
}
}
class MyRunnable4 implements Runnable{
public void run(){
for(int i=1;i<10;i++){
System.out.println("洗 "+i+"杯子去....");
try {
Thread.sleep(1000); //每运行一次,休眠一秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序