java 多线程

线程的三种状态: 新建, 运行, 就绪,阻塞,死亡
线程运行流程图
 
java中要使用线程有两种方法:
1. 继承Thread 类 并重写run函数 。通过start()函数启动
2. 实现Runable接口,并重写run函数。 通过创建new 一个Thread 然再start来启动
 
两个简单的java 线程例子 分别通过继承Thread 类 和 实现Runnable 接口的run 函数来实现线程:
package Threading;
 
/** java 多线程
* java中要使用线程有两种方法:
* 1. 继承Thread 类 并重写run函数
* 2. 实现Runable接口,并重写run函数
* Created by admin on 2017/7/30.
*/
public class JavaThread {
public static void main(String[] args){
Cat cat = new Cat();
// 通过start 方法运行线程, 会直接运行run 函数
cat.start();
Cat2 cat2 = new Cat2();
Thread thread = new Thread(cat2);
thread.start();
}
}
// 第一种方法,通过继承Thread 重写run 函数实现线程
class Cat extends Thread{
int times=0;
public void run(){
while (true){
// 让线程休眠 一秒. sleep 的参数是毫秒 1000 毫秒 等于 1 秒
// sleep 会导致线程进入阻塞(Blocked)状态
// 必须要使用try catch
try{
Thread.sleep(1000);
}catch (InterruptedException ie){
ie.printStackTrace();
}
times++;
System.out.println("Hello World"+times);
if (times == 10){
break;
}
}
}
}
// 通过实现Runnable接口来使用线程
class Cat2 implements Runnable{
@Override
public void run() {
for (int i=0; i<=10; i++){
try{
Thread.sleep(1000);
}catch (InterruptedException ie){
ie.printStackTrace();
}
System.out.println("Cat2 out"+i);
}
}
}
 
posted @ 2018-01-13 16:57  晴天小猫  阅读(156)  评论(0编辑  收藏  举报