Java线程总结(二)
自定义线程的数据可以共享,也可以不共享,这要看具体的实现方式。
1.不共享数据多线程实现方式:
public class MyThread extends Thread{ private int count = 4; public MyThread(String threadName){ this.setName(threadName); } @Override public void run(){ while (count > 0){ count = count - 1; System.out.println("由 " + Thread.currentThread().getName() + " 计算,count = " + count); try { Thread.sleep(1000); }catch (InterruptedException e){ e.printStackTrace(); } } } public static void main(String[] args) { MyThread threadA = new MyThread("A"); MyThread threadB = new MyThread("B"); MyThread threadC = new MyThread("C"); threadA.start(); threadB.start(); threadC.start(); } }
执行结果如下:
从结果上看,每个线程都是都是先打印3,再打印2,然后是1,0。由此可知各个线程都有一份变量count,不受其他线程的干扰。
2. 共享数据的多线程实现方式
public class MyThread extends Thread{ private int count = 4; @Override public void run(){ while (count > 0){ count = count - 1; System.out.println("由 " + Thread.currentThread().getName() + " 计算,count = " + count); try { Thread.sleep(1000); }catch (InterruptedException e){ e.printStackTrace(); } } } public static void main(String[] args) { MyThread myThread = new MyThread(); Thread a = new Thread(myThread,"A"); Thread b = new Thread(myThread,"B"); Thread c = new Thread(myThread,"C"); Thread d = new Thread(myThread,"D"); a.start(); b.start(); c.start(); d.start(); } }
执行结果如下:
由结果可知,A,B,C,D四个线程共享变量count