Java同步器示例

CountDownLatch

    public static void testCountDownLatch(String[] args) {
        final CountDownLatch start = new CountDownLatch(1);
        final CountDownLatch end = new CountDownLatch(4);

        final Runnable runnable = new Runnable() {
            @Override
            public void run() {

                try {
                    int id = new Random().nextInt(10);
                    start.await();
                    System.out.println(id + " Start");
                    Thread.sleep(id * 1000);
                    System.out.println(id + " end");
                    end.countDown();
                }
                catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        };

        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();

        start.countDown();
        try {
            end.await();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("All End");
    }

CyclicBarrier

    public static void testCyclicBarrier(String[] args) {
        final CyclicBarrier barrier = new CyclicBarrier(4, new Runnable() {
            @Override
            public void run() {
                System.out.println("In Handler");
            }
        });

        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                int id = new Random().nextInt(10);
                try {
                    for (int i = 0; i < 3; i++) {
                        System.out.println(id + " Start");
                        Thread.sleep(id * 1000);
                        System.out.println(id + " end");
                        barrier.await();
                    }
                }
                catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            }
        };

        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();
    }

Semaphore

    public static void testSemaphore(String[] args) {
        final Semaphore semaphore = new Semaphore(3);

        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                int id = new Random().nextInt(10);
                try {
                    semaphore.acquire();
                    System.out.println(id + " Start");
                    Thread.sleep(3000);
                    System.out.println(id + " end");

                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                finally {
                    semaphore.release();
                }
            }
        };

        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();
    }

SynchronousQueue

    public static void testSynchronousQueue(String[] args) {
        final SynchronousQueue<Integer> sq = new SynchronousQueue<>();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 3; i++) {
                        Thread.sleep(new Random().nextInt(5) * 1000);
                        sq.put(i);
                        System.out.println("Put " + i);
                    }
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    try {
                        int m = sq.take();
                        System.out.println("Take " + m);
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }).start();
    }

Exchanger

    public static void testExchanger(String[] args) {
        final Exchanger<byte[]> exchanger = new Exchanger<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    byte[] a = "123456".getBytes();
                    byte[] b = exchanger.exchange(a);
                    System.out.println("123456 ==> " + new String(b));
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    byte[] a = "456789".getBytes();
                    byte[] b = exchanger.exchange(a);
                    System.out.println("456789 ==> " + new String(b));
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }
时间: 2024-10-14 02:26:38

Java同步器示例的相关文章

jxl创建Excel文件java代码示例

记得要下载 并 导入 jxl.jar 包,免积分下载地址:http://download.csdn.net/detail/u010011052/7561041 package Test; import java.io.*; import jxl.*; import jxl.format.Colour; import jxl.write.*; public class JXLTest { private static WritableWorkbook book; private static Wr

JAVA接口示例

总感觉有点虚,但慢慢找到感觉了.将对象放进数组里,这就比较深入了. interface drawTest{ public void draw(); public void doAnyThing(); } class ParallelogramUserInterface extends QuadrangleUserInterface implements drawTest{ public void draw(){ System.out.println("Parallelogram.draw()&q

Java 同步示例

同步 1)同步方法 2)同步块 21) 实例变量 22) 类变量 锁定的内容 1)锁定类的某个特定实例 2)锁定类对象(类的所有实例) 一.同步类实例:同步方法 public class Demo { public synchronized void m1(){ //............... } public void m2(){ //............ synchronized(this){ //......... } //........ } } 这两种写法的效果是一样的,锁定的

JAVA多态示例

这多态,我觉得是最利害的.在开发大型程序中. 但,也是需要经过足够多的实践经验才能随心利用的. class Quadrangle{ private Quadrangle[] qtest = new Quadrangle[6]; private int nextIndex = 0; public void draw(Quadrangle q){ if(nextIndex < qtest.length){ qtest[nextIndex] = q; System.out.println(nextIn

Java线程示例 - 继承Thread类和实现Runnable接口

进程(Process)和线程(Thread)是程序运行的两个基本单元.Java并发编程更多的是和线程相关. 进程 进程是一个独立的执行单元,可将其视为一个程序或应用.然而,一个程序内部同事还包含多个进程.Java运行时环境就是一个单独的进程,在它内部还包含了作为进程的各种类和程序. 线程 可以将线程看做轻量级的进程.线程存在于进程当中,需要的资源开销较小.同一进程中的线程共享进程的资源. Java多线程 每一个Java引用都只要有一个线程 - 主线程(main thread).虽然后台还运行着许

Java Lambda示例

Lambda表达式 -- 用简单的方法实现只有一个函数的接口 Lambda syntax 1 2 3 (parameters) -> expression (parameters) -> statement (parameters) -> { statements } Lambda表达式实例 1 2 3 (intx,inty) -> x + y () -> System.out.println("hi "+ s); (String s) -> {in

Java定时任务示例

package com.my.timer; import java.util.Date; import java.util.TimerTask; public class myTask extends TimerTask { /** * 定时任务调用的方法,即处理业务的方法 */ @Override public void run() { System.out.println("定时任务执行了:" + new Date().toLocaleString()); } } package

RPC学习----Thrift快速入门和Java简单示例

一.什么是RPC? RPC(Remote Procedure Call Protocol)——远程过程调用协议,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议. RPC协议假定某些传输协议的存在,如TCP或UDP,为通信程序之间携带信息数据.在OSI网络通信模型中,RPC跨越了传输层和应用层.RPC使得开发包括网络分布式多程序在内的应用程序更加容易. 二.什么是Thrift? thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发.它结合了功能强大的软件堆栈和

Java发送邮件示例

利用Java发送邮件示例: 1.发送QQ邮件 1 import java.util.Properties; 2 import javax.mail.Message; 3 import javax.mail.MessagingException; 4 import javax.mail.Session; 5 import javax.mail.Transport; 6 import javax.mail.internet.AddressException; 7 import javax.mail.