[多线程学习]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