------- android培训、java培训、期待与您交流! ----------
线程和进程之间的关系:操作系统都支持进程的概念,所有运行中的任务通常都对应一个进程,当一个程序运行时,内部可能包含了多个顺序执行流,每个顺序执行流就是一个线程。
线程是进程的一个独立的控制单元。线程控制着进程的执行。
对于一个CPU而言,它在某个时间点只能执行一个程序,也就是说只能运行一个进程,但是因为CPU在进程之间的切换太快了,给我们的感觉就是同时在执行多个进程,当开启的程序足够多时,我们可以感觉到程序的运行速度下降。
注意在多线程编程时不要忘记,Java程序运行时默认的主线程main方法就是主线程的执行体。
Java中用Thread类代表线程,所有的对象都必须是Thread类或其子类的实例。
创建线程的方法有两种:第一种定义一个类继承Thread类并重写run方法,第二种实现Runnable接口并实现run实现run方法。
在创建线程时建议选择实现接口的方法。它们的区别在与:继承Thread类线程的代码存放在Thread子类run方法中。实现接口的线程代码存放在接口的子类的run方法中
继承的方法:因为继承在java中只能实现单继承(一个直接父类)因此通过继承方式定义多线程有局限性。
调用start()方法启动该线程并调用run()方法。
同步代码块 synchronized(Object obj){ 同步的代码} 其中参数为object类型的一个对象。
同步的前提:两个或者两个以上的线程。必须使用同一个锁。
等待唤醒机制:wait() notify()唤醒第一个等待的线程 notifyAll()唤醒所有等待线程包括己方的等待线程 他们操作的都是同一个锁上的线程。
例如:
class person
{
String name;
String sex;
Boolean flag=false;
int sum=0;
public synchronized void setN(){
while(flag==true){
try{System.out.println("存入线程等待");wait();}catch (Exception e){ }
}
if(sum==0){
this.name="小明";
this.sex="男";
sum=1;}
else{
this.name="小红";
this.sex="女";
sum=0;
}
this.flag=true;
try{notify();}catch(Exception e){}
}
public synchronized void getN(){
while(flag==false){
try{System.out.println("取出线程等待");wait();}catch(Exception e){}
}
System.out.println(this.name+"....."+this.sex);
this.flag=false;
try{notify();}catch(Exception e){}
}
}
class input implements Runnable
{
person p;
public input (person p){
this.p=p;
}
public void run(){
while(true){
p.setN();
}
}
}
class output implements Runnable
{
person p;
public output(person p){
this.p=p;
}
public void run(){
while(true){
p.getN();
}
}
}
public class ThreadDemo2
{
public static void main(String[] args){
person p=new person();
new Thread(new input(p)).start();
new Thread(new output(p)).start();
}
}
在JDK1.5中提供了多线程同步的升级解决方案:
将synchronized替换成了Lock操作。将Object中的wait,notify ,notifyAll替换成了Condition对象。该对象可以通过Lock的newCondition()方法获取。
通过该方法可以获取多个绑定在Lock上的Condition对象。
注意在使用Locket时应先导入java.util.concurrent.locks包。
setDaemon(boolean on)方法是将此线程设为守护线程,当前台线程结束后此线程自动结束。注意:这个方法要在start()方法之前使用。
例如:
class join implements Runnable
{
public void run(){
int sum=0;
while(true){
if(sum==60){
break;
}
sum++;
System.out.println(Thread.currentThread().getName()+"sum="+sum);
}
}
}
class ThreadDemo6
{
public static void main(String[] args)
{
join j=new join();
Thread t=new Thread(j);
t.setDaemon(true);
t.start();
for(int x=0;x<60;x++){
System.out.println("x===:"+x);
}
System.out.println("over");
}
}
某次的结果为:
证明了,当主线程结束后,守护线程就自动结束了。
join()方法:当A线程遇到了B线程的.join()方法时,会释放执行权,等B线程执行完毕后再执行A线程。这个方法可以用来临时加入一个线程执行。
setPriority(int newPriority)更改线程的优先级。默认优先级为5,优先级一共十级。其中1,5,10作用最明显,因此定义成了三个全局静态常量
MAX_PRIORITY:线程可以具有的最高优先级。 ,MIN_PRIORITY:线程可以具有的最低优先级。NORM_PRIORITY:分配给线程的默认优先级。
注意优先级代表得到CPU执行权的几率大。
static void
yield();暂停当前正在执行的线程对象,并执行其他线程。