自定义线程的数据能够共享,也能够不共享,这要看具体的实现方式。多线程
1.不共享数据多线程实现方式:ide
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(); } }
执行结果以下:this
从结果上看,每一个线程都是都是先打印3,再打印2,而后是1,0。由此可知各个线程都有一份变量count,不受其余线程的干扰。spa
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(); } }
执行结果以下:code
由结果可知,A,B,C,D四个线程共享变量countblog