Java多线程

1.Java多线程传统实现方式

原链接地址:http://blog.csdn.net/kingzone_2008/article/details/44571181

public class TraditionalThread {

    public static void main(String[] args) {

        /*
         * 方法1:覆盖父类Thread的run方法
         */
        Thread thread = new Thread() {

            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("输出1:" +     Thread.currentThread().getName());
                    System.out.println("输出2:" + this.getName());
                }
            }

        };
        thread.start();

        /*
         * 方法2:实现Runnable接口,实现其run方法
         */
        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("输出1:" + Thread.currentThread().getName());
//                  System.out.println("输出2:" + this.getName());
                }
            }

        });
        thread2.start();
  }
}

2.定时器类:Timer类和TimerTask类

原链接地址:http://blog.csdn.net/kingzone_2008/article/details/45270171

2.1指定时间间隔后执行任务

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TraditionalTimerTest {

    public static void main(String[] args) {

        // 启动定时器线程,并在10000毫秒后执行TimerTask实例的run方法
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                System.out.println("bombing!");

            }
        }, 10000);

        while(true) {
            System.out.println("时钟时间:" + new Date().getSeconds());
            try {
                Thread.sleep(1000);// 主线程每隔1秒钟,打印当前时钟时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

2.2指定时间间隔后循环执行任务

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TraditionalTimerTest {

    public static void main(String[] args) {
        // 启动定时器线程,并在10000毫秒后开始,每隔3000毫秒执行一次定时任务
        new Timer().schedule(new TimerTask() {// 定时任务

            @Override
            public void run() {
                System.out.println("bombing!");

            }
        }, 10000, 3000);

        while(true) {
            System.out.println("时钟时间:" + new Date().getSeconds());
            try {
                Thread.sleep(1000);// 主线程每隔1秒钟,打印当前时钟时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

2.3更灵活地间隔

//定义两个/多个TimerTask类
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TraditionalTimerTest {

    public static void main(String[] args) {

        new Timer().schedule(new MyTimerTask1(), 2000);

        while(true) {
            System.out.println("时钟时间:" + new Date().getSeconds());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
class MyTimerTask1 extends TimerTask {

    @Override
    public void run() {
        System.out.println("Task1");
        new Timer().schedule(new MyTimerTask2(), 2000);// 启动定时任务2
    }

}
class MyTimerTask2 extends TimerTask {

    @Override
    public void run() {
        System.out.println("Task2");
        new Timer().schedule(new MyTimerTask1(), 4000);// 启动定时任务1
    }

}

3.Java传统线程互斥技术

原链接地址:http://blog.csdn.net/kingzone_2008/article/details/48166731
3.1以this作为锁对象

实现方式
synchronized(this){…}
synchronized实例方法
适用情况
适用于使用类的同一个实例(对象)作为锁对象。下面情况不适用:
若上述代码中第26行和第39行,改为
new Printer().output(“<相应字符串>”);
则无法使用本方法实现线程互斥,而须采用第2种方法。

3.2以Outputer.class作为锁对象

Outputer类的字节码对象由jvm自动加载。
实现方式
synchronized(Outputer.class){…}
static synchronized方法
适用情况
适用于整个类的所有对象都需要互斥访问的情况。

3.3以自定义的对象作为所对象

实现方式
synchronized(<自定义锁对象>){…}
适用情况
同一个类中代码块或者方法的互斥,一般可以用第1种和第2种方法替换。当出现需要在多个类(或者多个类的实例)之间进行互斥控制时,可能需要采用本方法。

3.4一些代码

public class TraditionalThreadSynchronized {

    public static void main(String[] args) {
        new TraditionalThreadSynchronized().foo();
    }

    private void foo() {
        // printer须是final的,否则无法编译。这主要是为了保证printer的一致性。
        final Printer printer = new Printer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    /* 
                     * Cannot refer to a non-final variable printer
                     * inside an inner class defined in a different method
                     * 更多内容可参阅java8 lambda表达式(闭包)相关知识
                     */
                    printer.output("123456789");
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    printer.output("abcdefghi");
                }
            }
        }).start();
    }

    static class Printer {
        String _lock = "";
        public void output(String name) {
            int len = name.length();
            // 同步代码块

            /* 方法1:
             * 以this作为锁对象,
             * 与使用this加锁的代码块或synchronized方法互斥
             */
            // synchronized(this) {

            /* 方法2:
             * 以Outputer类的字节码对象(该对象由虚拟机自动创建)作为锁对象,
             * 与使用Outputer.class加锁的代码块或static synchronized方法互斥
             */
            // synchronized(Outputer.class) {

            /* 方法3:
             * 以自定义对象作为锁对象,
             * 与使用_lock加锁的代码块互斥
             */
            synchronized(_lock) {
                for(int i=0; i<len; i++) {
                    System.out.print(name.charAt(i));
                }
                System.out.println();
            }
        }

        // 同步方法,相当于synchronized(this){}
        public synchronized void output2(String name) {
            int len = name.length();
            for(int i=0; i<len; i++) {
                System.out.print(name.charAt(i));
            }
            System.out.println();
        }

        // 静态同步方法,相当于synchronized(Outputer.class){}
        public static synchronized void output3(String name) {
            int len = name.length();
            for(int i=0; i<len; i++) {
                System.out.print(name.charAt(i));
            }
            System.out.println();
        }
    }
}

4.Java传统线程同步通信技术

原链接地址:
http://blog.csdn.net/kingzone_2008/article/details/49853341

public class TraditionalThreadCommunication {

    public static void main(String[] args) {
        // 必须声明为final
        final Business business = new Business();
        new Thread(
                new Runnable() {

                    @Override
                    public void run() {
                        for(int i=1; i<=50; i++) {
                            business.sub(i);
                        }
                    }

                }
                ).start();

        for(int i=1; i<=50; i++) {
            business.main(i);
        }
    }

}

class Business {
    // 该变量用于线程间通信
    private boolean bShouldSub = true;
    public synchronized void sub(int i) {
        if(!bShouldSub) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for(int j=1; j<=10; j++) {
            System.out.println("sub thread sequence of " 
                                + j + ", loop of " + i);
        }
        bShouldSub = false;
        this.notify();
    }
    public synchronized void main(int i) {
        if(bShouldSub) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for(int j=1; j<=100; j++) {
            System.out.println("main thread sequence of " 
                                + j + ", loop of " + i);
        }
        bShouldSub = true;//执行完后,将自己wait()
        this.notify();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值