一、建立线程的两种方式:this
(1)建立Thread类的子类,重写run方法线程
class Thread1 extends Thread{ public void run(){ 重写方法体 } }对象
在main方法中:接口
Thread1 t1 = new Thread1 (); 同步
t1.start();string
(2)实现Runnable接口,重写run方法,再传入Thread类的实例参数中class
class Thread2 implements Runnable{ public void run(){ 重写方法体} }方法
在main方法中:im
Thread2 t2 = new Thread2 ();call
Thread t = new Thread(t2);
t.start();
二、线程同步
(1)同步方法:使调用该方法的线程均能得到对象的锁
class Share{ synchronized void print(String str){ 方法体 }}
被synchronized 的方法,一旦一个线程进入实例的同步方法中,直到当前线程执行完这个方法,其余线程才能进入。但该实例的非同步方法仍是能够被其余线程调用的
(2)同步块
关联(1)中的类,class caller implements Runnable{
string str;
Share s;
Thread t;
public caller(Share s,String str){
this.s = s;
this.str = str;
t = new Thread(this);
t.start();
}
public void run (){
synchronized(s){ //同步share对象
s.print(str);
}
}
}