多线程

1继承Thread 

package cn.mym.basic.util;

public class Thread1 extends Thread {
private int count=5;
private String name;
public Thread1(String name) {
this.name=name;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + "运行 count= " + count--);
try {
sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread1 mTh1=new Thread1("A");
Thread1 mTh2=new Thread1("B");
mTh1.start();
mTh2.start();
}
}

运行结果:

2.实现Runnable接口

package cn.mym.basic.util;

public class Runnable1 implements Runnable{
private int count=15;

public static void main(String[] args) {

Runnable1 my = new Runnable1();
new Thread(my, "C").start();//同一个mt,但是在Thread中就不可以,如果用同一个实例化对象mt,就会出现异常
new Thread(my, "D").start();
new Thread(my, "E").start();
}

public void run() {
for (int i = 0; i < 6; i++) {
if(count > 0 ){
System.out.println(Thread.currentThread().getName() + "运行 count= " + count--);
}
try {
Thread.sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

 运行结果:

使用第二种方式可以实现资源的共享。

posted on 2017-02-17 16:46  依米欧  阅读(159)  评论(0编辑  收藏  举报