hadoop06---多線程,synchronized
阿新 • • 發佈:2018-05-08
test pri g++ getname trac 繼承 import rand runnable
.1.1. 實現線程的兩種方式
1、繼承Thread的方式
見代碼MyThreadWithExtends
2、聲明實現 Runnable 接口的方式
見代碼MyThreadWithImpliment
package cn.itcast_01_mythread.thread.testThread; import java.util.Random; public class MyThreadWithExtends extends Thread { String flag; float g = 1; public MyThreadWithExtends(String flag){this.flag = flag; } @Override public void run() {//並沒有看出來線程1和線程2各自獨有的。 float f = 1; f++;//f是線程的值 g++;//g是堆對象的值 System.out.println("f:"+f); System.out.println("g:"+g); String tname = Thread.currentThread().getName(); System.out.println(tname+"線程的run方法被調用……"); Random random = new Random(); for(int i=0;i<2;i++){ try { Thread.sleep(random.nextInt(10)*100); System.out.println(tname+ "...."+ flag);//flag是堆對象的值,不同的線程和相同的線程來調用這個方法,都是對象裏面的值。 } catch (InterruptedException e) { e.printStackTrace(); } } }public static void main(String[] args) { Thread thread1 = new MyThreadWithExtends("a"); Thread thread2 = new MyThreadWithExtends("b"); /* 有獨立的變量作用域。 run方法是共用的,但是不同線程調的。 f:2.0 f:2.0 g:2.0 g:2.0 Thread-1線程的run方法被調用…… Thread-0線程的run方法被調用…… Thread-0....a Thread-1....b Thread-0....a Thread-1....b */ // thread1.start(); // thread2.start(); /** 如果是調用thread的run方法,則只是一個普通的方法調用,不會開啟新的線程 都在主線程運行,所有的變量共享。thread1,thread2是2個堆中的變量。 run方法是共用的,但是都是主線程調的。 f:2.0 g:2.0 main線程的run方法被調用…… main....a main....a f:2.0 g:2.0 main線程的run方法被調用…… main....b main....b */ thread1.run(); thread2.run(); } }
package cn.itcast_01_mythread.thread.testThread; public class MyThreadWithImpliment implements Runnable { int x; public MyThreadWithImpliment(int x) { this.x = x; } @Override public void run() { String name = Thread.currentThread().getName(); System.out.println("線程" + name + "的run方法被調用……"); for (int i = 0; i < 10; i++) { System.out.println(x); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { Thread thread1 = new Thread(new MyThreadWithImpliment(1), "thread-1"); Thread thread2 = new Thread(new MyThreadWithImpliment(2), "thread-2"); // thread1.start(); // thread2.start(); // 註意調用run和調用start的區別,直接調用run,則都運行在main線程中 thread1.run(); thread2.run(); } }
hadoop06---多線程,synchronized