标签:
多线程 : 多执行路径的方法。多线程来达到同样的问题,当多个执行代码,来说会减少。
创建线程有两个方法
方法1.将类声明为Thread的子类。该子类重写Thread类的run方法。
即定义一个类继承Thread,覆盖run方法。
当中run方法是封装自己定义线程执行任务的函数。
例:class method extends Thread{
public void run(){
for(i=0;i<10;i++){
syatem.out.println("i="+i);
}
}
}
class Demo{
public static void main(String[] args){
method m=new method();
m.start();//开启线程,调用run方法。
}
}
方式2:1.定义一个类实现Runnable接口。
2.覆盖接口中的run方法,将线程的任务代码封装到run方法中。
3.通过Thread 类创建线程对象,并将runnable接口的子类对象
作为Thread类的构造函数的參数进行传递,这是由于线程的任务
都封装在Runnable接口子类对象的run方法中,所以要在线程对象
时,就必需要明白要执行的任务。
4.调用Thread类中的start方法开启线程。
例:class Demo implements Runnabie{
public void run(){
for(int x=0;x<20;x++){
system.out.println("x="+x);
}
}
}
class Demo implements Runnabie{
public static void main(String[] args){
Demo d=new Demo();
Thread t=new Thread(d);
t.start();
}
}
在多线程执行的过程中,其它线程也參与了运算,将会导致线程安全问题的产生,这是就用到了同步代码块
和同步函数。例如以下例。
练习:等待唤醒机制
class Resource{
private String name;
private String sex;
private boolean flag=false;
public synchronized void set(String name,String sex){
if(flag)
try{wait();}catch(InterruptedException e){}
this.name=name;
this.sex=sex;
flag=true;
notify();
}
public synchronized void out(){
if(!flag)
try{wait();}catch(InterruptedException e){}
System.out.println(name+"....."+sex);
flag=false;
notify();
}
}
class Input implements Runnable {
Resource r;
Input(Resource r){
this.r=r;
}
public void run(){
int x=0;
while(true){
if(x==0){
r.set("老婆","1314");
}
else{
r.set("laogong","3344");
}
x=(x+1)%2;
}
}
}
//输出
class Output implements Runnable{
Resource r;
Output(Resource r){
this.r=r;
}
public void run(){
while(true){
r.out();
}
}
}
class Test{
public static void main(String args[]){
Resource r =new Resource();
Input a = new Input(r);
Output b = new Output(r);
Thread t1= new Thread(a);
Thread t2= new Thread(b);
t1.start();
t2.start();
}
}
标签:
原文地址:http://www.cnblogs.com/bhlsheji/p/4601655.html