来我们看第一个例子 顺便讲讲start与run的区别
public class TestThread1 { public static void main(String args[]) { Runner1 r = new Runner1(); r.start(); //r.run(); for(int i=0; i<100; i++) { System.out.println("Main Thread:------" + i); } } } class Runner1 extends Thread { public void run() { for(int i=0; i<100; i++) { System.out.println("Runner1 :" + i); } } }运行的结果是 Main Thread..与Runner1...交替输出
这时候 就运行了两个线程 一个主线程 一个r线程
如果把r.start改成r.run那么就是先打出100个Runner1..然后才是100个Main Thread
为什么?
大家仔细看看如果我们调用r.run() 那不就是函数调用了么!!!
所以一句话我们自定义的线程必须实现run方法 但调用的时候得是start()!
再看另一种定义线程的方式
public class TestThread1 { public static void main(String args[]) { Runner1 r = new Runner1(); Thread t = new Thread(r); t.start(); for(int i=0; i<50; i++) { System.out.println("Main Thread:------" + i); } } } class Runner1 implements Runnable { public void run() { for(int i=0; i<50; i++) { System.out.println("Runner1 :" + i); } } }
public class TestThread3{ public static void main(String args[]) { Runner3 r = new Runner3(); Thread t = new Thread(r); t.start(); } } class Runner3 implements Runnable { public void run() { for(int i=0; i<30; i++) { if(i%10==0 && i!=0) { try{ Thread.sleep(2000); }catch(InterruptedException e){} } System.out.println("No. " + i); } } }
public class TestInterrupt { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); try {Thread.sleep(10000);} catch (InterruptedException e) {} thread.interrupt(); } } class MyThread extends Thread { boolean flag = true; public void run(){ while(true){ System.out.println("==="+new Date()+"==="); try { sleep(1000); } catch (InterruptedException e) { return; } } } }
public class TestInterrupt { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); try {Thread.sleep(10000);} catch (InterruptedException e) {} thread.interrupt(); } } class MyThread extends Thread { boolean flag = true; public void run(){ while(true){ System.out.println("==="+new Date()+"==="); try { sleep(1000); } catch (InterruptedException e) { return; } } } }
public class TestInterrupt { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); try {Thread.sleep(10000);} catch (InterruptedException e) {} thread.interrupt(); } } class MyThread extends Thread { boolean flag = true; public void run(){ while(true){ System.out.println("==="+new Date()+"==="); try { sleep(1000); } catch (InterruptedException e) { return; } } } }
public class TestPriority { public static void main(String[] args) { Thread t1 = new Thread(new T1()); Thread t2 = new Thread(new T2()); t1.setPriority(Thread.NORM_PRIORITY + 3); t1.start(); t2.start(); } } class T1 implements Runnable { public void run() { for(int i=0; i<1000; i++) System.out.println("T1: " + i); } } class T2 implements Runnable { public void run() { for(int i=0; i<1000; i++) System.out.println("------T2: " + i); } }
原文地址:http://blog.csdn.net/dlf123321/article/details/40110713