[多线程学习]2017.02.21
来源:互联网 发布:淘宝问卷调查报告 编辑:程序博客网 时间:2024/06/05 10:56
在家呆了一天,然后出去坐地铁。。。为啥宅男要坐地铁呢?因为我买了地铁月票。。。不坐总感觉亏。宅男呀。。。
今天动手写点多线程代码:
先看看Runnable接口是怎么用的。先建两个类,一个是测试类(PeopleTest),还有个是构建对象的类(PeopleThread)
PeopleThread实现了Runnable接口,所以可以被线程类所调用,功能其实和Thread的子类是一样的。
PeopleThread
package ts;public class PeopleThread implements Runnable {/** * decide how long will it sleep */private final int sleepTime;/** * people say */private final String speak;/** * Contains code that tread will run */@Overridepublic void run() {try // put thread to sleep for sleepTime amount of time{System.out.printf("%s going to sleep for %d milliseconds.\n",speak, sleepTime);Thread.sleep(sleepTime); // put thread to sleep} // end trycatch (InterruptedException exception){System.out.printf("%s %s\n", speak,"terminated prematurely due to interruption");} // end catch// print people nameSystem.out.printf("%s done sleeping\n", speak);}/** * Constructor function * * @param name people's name */public PeopleThread(String name, int sleep) {speak = name;sleepTime = sleep;}}
PeopleTest:
package ts;public class PeopleTest {public static void main(String[] args) {Thread John = new Thread(new PeopleThread("John", 5000));Thread Alice = new Thread(new PeopleThread("Alice", 1000));John.start();Alice.start();}}
运行以后:
发现Alice睡得早,醒的早。John睡得晚,醒的晚。Alice线程进行休眠时候,John线程开始启动。。
修改代码:
package ts;public class PeopleTest {public static void main(String[] args) {Thread John = new Thread(new PeopleThread("John", 5000));Thread Alice = new Thread(new PeopleThread("Alice", 1000));Alice.start();// interrupt AliceAlice.interrupt();John.start();}}
先到这吧。。。哎。。。看到那些比我早来半年同学拿着将近1W dollar每月的实习工资。。。流口水呀!!!!
哎,洗澡!
0 0
- [多线程学习]2017.02.21
- 【多线程学习】2017.02.20
- 学习多线程
- 多线程学习
- 多线程学习
- 多线程学习
- 多线程学习
- 多线程学习
- 多线程学习
- 学习多线程
- 多线程学习
- 多线程学习
- 多线程学习
- 多线程学习
- 多线程学习
- 多线程学习
- 多线程学习
- 多线程学习
- Jenkins QuickStart
- 零基础写Java知乎爬虫之进阶篇
- JS rotate
- photoshop第十六章:制作商业广告效果
- NSSearchPathForDirectoriesInDomain函数使用
- [多线程学习]2017.02.21
- 【ZIP格式分析】 文件名乱码
- FastJson的简单使用
- 如何判断当前界面是否属于某个apk,或具体到某个Activity
- ASM 翻译系列第四弹:高级知识kfed元数据编辑器
- Longest Palindromic Substring--求字符串最长回文子串
- android使用startActivityForResult跳转Activity并回传值
- pfx证书提取公私钥的方法
- oracle之数据类型number分析