第九区-Jquery超级群

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 273|回复: 0

想说下多线程。。。 [复制链接]

Rank: 7Rank: 7Rank: 7

发表于 2011-7-14 16:40:02 |显示全部楼层
本帖最后由 king 于 2011-7-14 16:42 编辑

线程是指进程中的一个执行流程,一个进程中可以运行多个线程。比如java.exe进程中可以运行很多线程。线程总是属于某个进程,进程中的多个线程共享进程的内存。
public class TestThread extends Thread{
    public TestThread(String name) {
        super(name);
    }

    public void run() {
        for(int i = 0;i<5;i++){
            for(long k= 0; k <100000000;k++);
            System.out.println(this.getName()+" :"+i);
        }
    }

    public static void main(String[] args) {
        Thread t1 = new TestThread("阿三");
        Thread t2 = new TestThread("李四");
        t1.start();
        t2.start();
    }
}

阿三 :0
李四 :0
阿三 :1
李四 :1
阿三 :2
李四 :2
阿三 :3
阿三 :4
李四 :3
李四 :4

对于上面的多线程程序代码来说,输出的结果是不确定的。其中的一条语句for(long k= 0; k <100000000;k++);是用来模拟一个非常耗时的操作的。
public class TestThread extends Thread {

    public void run() {
             for(int i = 0;i<5;i++){
            for(long k= 0; k <100000000;k++);

            try{
                 Thread.sleep(3);
             }catch
            System.out.println(this.getName()+" :"+i);
        }
    }

    public static void main(String[] args) {
        new
TestThread().start();
    }
}

这样,线程在每次执行过程中,总会睡眠3毫秒,睡眠了,其他的线程就有机会执行了。
多线程是同步执行多个任务、、、在执行过程中会对线程造成值的破坏
public class Konf {
    private int x = 100;

    public int getX() {
        return x;
    }

    public int fix(int y) {
        x = x - y;
        return x;
    }
}

public class KonfRunnable implements Runnable {
    private
Konf konf = new Konf ();

    public static void main(String[] args) {
        
KonfRunnable r = new KonfRunnable ();
        Thread ta = new Thread(r, "Thread1");
        Thread tb = new Thread(r, "Thread2");
        ta.start();
        tb.start();
    }

    public void run() {
        for (int i = 0; i < 3; i++) {
            this.fix(30);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " : 当前
konf对象的x值= " +
konf.getX());
        }
    }

    public int fix(int y) {
        return
konf .fix(y);
    }
}

上面会出现不合理的值 是因为多线程时会对数据产生更改、、、、在进行多线程的时候不放对sleep延时3秒。。。在把fix里的计算锁定、、、、
    public int fix(int y) {
         synchronized(this){
            x=x-y;
        }

         return x;
}
    }

您需要登录后才可以回帖 登录 | 立即注册

Archiver|第九区-Jquery超级群    点击这里加入此群 点击这里加入此群

GMT+8, 2012-2-8 09:52 , Processed in 0.063601 second(s), 15 queries .

Powered by Discuz! X2

© 2001-2011 Comsenz Inc.

回顶部