1.定義線程的兩種傳統方式。
package thread;
public class TradionalThreadTest
{
public static void main(String[] args)
{
//線程創建方法1:new thread的子類
new Thread(){
@Override
public void run()
{
while(true){
System.out.println("current thread(子類) is " + Thread.currentThread().getName());
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
//線程創建方法2:new Runnable作爲參數(一般採用這個)
//如果兩種方法都採用了,根據面向對象方法只會進行子類的run方法。
new Thread(new Runnable() {
public void run()
{
while(true){
System.out.println("current thread(runnable) is " + Thread.currentThread().getName());
try
{
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}){
@Override
public void run()
{
while(true){
System.out.println("current thread(子類2) is " + Thread.currentThread().getName());
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}.start();
}
}
2. 定時器 timer,timetask類
3. 線程互斥(synchronized),wait與notify通信。
4. 線程數據共享方式見附件(QQ圖片20140716223607.jpg)
5. ThreadLocal類共享線程間數據變量。利用ThreadLocal把共享對象封裝起來(類似單例的實現方式)
class ThreadScopeStudent{
private String name;
private Long id;
private static ThreadLocal<ThreadScopeStudent> map = new ThreadLocal<ThreadScopeStudent>();
private ThreadScopeStudent(){
}
public static ThreadScopeStudent getThreadStudent(){
ThreadScopeStudent student = map.get();
if(null == student){
student =new ThreadScopeStudent();
map.set(student);
}
return student;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
}
---課程 來自 張孝祥老師