我把我自己感觉有问题的地方写了一下,关于线程的一些实用的东西,供大家参考,一同进步,一起共勉。
一个是实现Runnable接口实现run()方法,一个是new Thread() 实现run() 方法和继承extends Thread 实现run()方法
小例子见笑:
1、继承Thread 实现run()方法
public class ThreadDemo01 {
public static void main(String[] args) {
Thread t1 = new Person1();
Thread t2 = new Person2();
t1.start(); //启动线程调用start()方法
t2.start(); //两个线程是异步的,不是同步的。
}
}
class Person1 extends Thread{
public void run(){
for(int i = 0;i<1000;i++){
System.out.println("你是谁");
}
}
}
class Person2 extends Thread{
public void run(){
for(int i = 0;i<1000;i++){
System.out.println("我是收电费的");
}
}
}
2、实现Runnable接口实现run()方法
public class ThreadDemo02 {
public static void main(String[] args) {
Runnable runnable1 = new Runnable1();
Runnable runnable2 = new Runnable2();
Thread t1 = new Thread(runnable1);
Thread t2 = new Thread(runnable2);
t1.start();
t2.start();
}
}
class Runnable1 implements Runnable{
public void run(){
for(int i = 0;i<1000;i++){
System.out.println("你是谁呀");
}
}
}
class Runnable2 implements Runnable{
public void run(){
for(int i = 0;i<1000;i++){
System.out.println("我是修电表的");
}
}
}
3、new Thread() 实现run() 方法
public class DaemonThreadDemo {
public static void main(String[] args) {
Thread rose = new Thread(){
public void run(){
for(int i = 0;i<10;i++){
System.out.println("rose:let me go");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("rose:啊啊啊啊啊啊AAAAAA");
System.out.println("扑通");
}
};
Thread jack = new Thread(){
public void run(){
while(true){
System.out.println("jack:you jump!i jump");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
jack.setDaemon(true); //设置为后台线程,在写在start()方法之前
rose.start();
jack.start();
}
} |