java 多线程测试

join测试

package lmlc.test;

public class TestJoin {
    public static  void main(String args[]) {
        Myrunner mr = new Myrunner();
        Thread t = new Thread(mr);
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i =0;i<50;i++) {
            System.out.println("main" + i);
        }
    }
}

class Myrunner implements Runnable {
    public void run() {
        for (int i=0;i<50;i++) {
            System.out.println("subthread " + i);
        }
    }
}

先将上面的join删除,看到输出,主线程与子线程的执行是重叠的,添加join后,子线程先执行,执行完成后在执行主线程的。

为了在多线程的情况下,每个线程在执行一段代码的是能,能顺序执行,使用synchronized
摘自:
http://blog.csdn.net/xiao__gui/article/details/8188833

package lmlc.test;

class Sync {

    public void test() {
        synchronized (this) {
            System.out.println("test开始..");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("test结束..");
        }
    }
}

class MyThread extends Thread {
    private Sync sync;
    public MyThread(Sync sync) {
        this.sync=sync;
    }
    public void run() {

        sync.test();
    }
}

public class Main {

    public static void main(String[] args) {
        Sync sync = new Sync();
        for (int i = 0; i < 3; i++) {
            Thread thread = new MyThread(sync);
            thread.start();
        }
    }
}

这2个组合是在同步方法块中使用,被锁定的对象调用wait方法,当前线程被阻塞并放弃该对象的互斥锁,其他线程可以有机会获得执行机会,调用wait被阻塞的线程,会被添加到一个特殊的对象等待队列中,直到调用wait方法的对象在其他的线程中调用notify或notifyall方法

package cn.javass.c13;

public class WaitReleaseLock {
public static void main(String[] args) {
ThreadA4 ta = new ThreadA4(true);
Thread b = new Thread(ta);
Thread a = new Thread(ta);
b.start();
a.start();
}
}
class ThreadA4 implements Runnable {
private boolean needWait = false;

public ThreadA4(boolean needWait) {
    this.needWait = needWait;
}

public void run() {
    synchronized (this) {
        for (int i = 0; i < 10; i++) {
            System.out
                    .println(Thread.currentThread().getName() + ",i=" + i);
            try {
                if (needWait) {
                    this.needWait = false;
                    wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //this.notify();
    }
}

}

这个例子中把notify注释掉,导致线程一直等待,挂在那里了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值