标签:style blog color ar for sp div 2014 art
1
Thread Runnable接口
1 public class wori 2 { 3 public static void main(String args[]) 4 { 5 Animal a = new Animal(); 6 Thread b = new Thread(a); 7 b.start(); //在执行时不会等到方法执行结束再往下执行,而是同时向下执行 8 for(int i = 10; i > 0; i--) 9 { 10 System.out.println(i); 11 } 12 13 } 14 } 15 16 class Animal implements Runnable 17 { 18 public void run() 19 { 20 for(int i = 0; i < 100000; i++) 21 { 22 System.out.println(i); 23 } 24 } 25 }
2
继承Thread
1 public class wori 2 { 3 public static void main(String args[]) 4 { 5 Animal a = new Animal(); 6 7 a.start(); 8 for(int i = 10; i > 0; i--) 9 { 10 System.out.println(i); 11 } 12 13 } 14 } 15 16 class Animal extends Thread 17 { 18 public void run() 19 { 20 for(int i = 0; i < 100000; i++) 21 { 22 System.out.println(i); 23 } 24 } 25 }
3
线程结束
让run结束就行
void shutdown()
{
temp =false();
}
4
synchronized锁定 对象 ,不让其他同对象的线程访问
1 public class wori implements Runnable 2 { 3 Animal a = new Animal(); 4 public static void main(String args[]) 5 { 6 wori b = new wori(); 7 Thread c = new Thread(b); 8 Thread d = new Thread(b); 9 c.start(); 10 d.start(); 11 } 12 public void run() 13 { 14 a.show(); 15 } 16 } 17 18 class Animal 19 { 20 static int n = 0; 21 synchronized void show() 22 { 23 n++; 24 System.out.println(n); 25 } 26 }
或者
synchronized(this)
{
}
反正记住就是锁住对象,实现线程的同步
synchronized方法只限制单线程访问该方法,其他不是synchronized可以随意访问
同一对象访问了一个synchronized方法的同时,该对象的其他线程不能访问其他synchronized
标签:style blog color ar for sp div 2014 art
原文地址:http://www.cnblogs.com/melon2014/p/3997658.html