zoukankan      html  css  js  c++  java
  • Java-笔记17

     

    java 官方文档介绍

    public
    class Thread extends Object implements RunnableA thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon. When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs: The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place. All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method. There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started. For example, a thread that computes primes larger than a stated value could be written as follows: -------------------------------------------------------------------------------- class PrimeThread extends Thread { long minPrime; PrimeThread(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime . . . } } -------------------------------------------------------------------------------- The following code would then create a thread and start it running: PrimeThread p = new PrimeThread(143); p.start(); The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started. The same example in this other style looks like the following: -------------------------------------------------------------------------------- class PrimeRun implements Runnable { long minPrime; PrimeRun(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime . . . } } -------------------------------------------------------------------------------- The following code would then create a thread and start it running: PrimeRun p = new PrimeRun(143); new Thread(p).start(); Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it. Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.
    package com.lxl.java;
    
    /**
     * 多线程的创建,方式一:继承于Thread类
     * 1. 创建一个继承于Thread类的子类
     * 2. 重写Thread类的run() --> 将此线程执行的操作声明在run()中
     * 3. 创建Thread类的子类的对象
     * 4. 通过此对象调用start()
     * <p>
     * 例子:遍历100以内的所有的偶数
     * @author LXL
     * @create 2019-05-27 17:11
     */
    
    class MyThread extends Thread {
        //2. 重写Thread类的run()
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                if(i % 2 == 0){
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                }
            }
        }
    }
    
    public class ThreadTest {
        public static void main(String[] args) {
            //3. 创建Thread类的子类的对象
            MyThread t1 = new MyThread();
    
            //4.通过此对象调用start():①启动当前线程 ② 调用当前线程的run()
            t1.start();
            //问题一:我们不能通过直接调用run()的方式启动线程。
    //        t1.run();
    
            //问题二:再启动一个线程,遍历100以内的偶数。不可以还让已经start()的线程去执行。会报IllegalThreadStateException
    //        t1.start();
            //我们需要重新创建一个线程的对象
            MyThread t2 = new MyThread();
            t2.start();
    
    
            //如下操作仍然是在main线程中执行的。
            for (int i = 0; i < 100; i++) {
                if(i % 2 == 0){
                    System.out.println(Thread.currentThread().getName() + ":" + i + "***********main()************");
                }
            }
        }
    }
    package com.lxl.exer;
    
    /**
     * 练习:创建两个分线程,其中一个线程遍历100以内的偶数,另一个线程遍历100以内的奇数
     *
     *
     * @author LXL
     * @create 2019-05-27 17:14
     */
    public class ThreadDemo {
        public static void main(String[] args) {
    //        MyThread1 m1 = new MyThread1();
    //        MyThread2 m2 = new MyThread2();
    //
    //        m1.start();
    //        m2.start();
    
            //创建Thread类的匿名子类的方法
            new Thread(){
                @Override
                public void run() {
                    for (int i = 0; i < 100; i++) {
                        if(i % 2 == 0){
                            System.out.println(Thread.currentThread().getName() + ":" + i);
    
                        }
                    }
    
                }
            }.start();
    
    
            new Thread(){
                @Override
                public void run() {
                    for (int i = 0; i < 100; i++) {
                        if(i % 2 != 0){
                            System.out.println(Thread.currentThread().getName() + ":" + i);
    
                        }
                    }
    
                }
            }.start();
    
        }
    
    }
    
    
    class MyThread1 extends Thread{
    
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                if(i % 2 == 0){
                    System.out.println(Thread.currentThread().getName() + ":" + i);
    
                }
            }
    
        }
    }
    
    
    class MyThread2 extends Thread{
    
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                if(i % 2 != 0){
                    System.out.println(Thread.currentThread().getName() + ":" + i);
    
                }
            }
    
        }
    }

     

    package com.lxl.java;
    
    /**
     * 测试Thread中的常用方法:
     * 1. start():启动当前线程;调用当前线程的run()
     * 2. run():通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
     * 3. currentThread():静态方法,返回当前代码的线程
     * 4. getName():获取当前线程的名字
     * 5. setName():设置当前线程的名字
     * 6. yield():释放当前CPU的执行权
     * 7. join():在线程A中调用线程B的join(),此时线程A就进入阻塞状态,直到线程B完全执行完以后,
     *               线程A才会结束阻塞
     * 8. stop():已过时。当执行此方法时,强制结束当前进程。
     * 9. sleep(long millitime):让当前线程"睡眠"指定的millitime毫秒.在指定的时间内millitime毫秒时间内,
     *                              当前线程是阻塞状态
     * 10. isAlive():判断当前线程是否存活
     *
     * 线程的优先级:
     * 1.
     * MAX_PRIORITY:10
     * MIN _PRIORITY:1
     * NORM_PRIORITY:5  -->默认优先级
     *
     * 2.如何获取和设置当前线程的优先级:
     *   getPriority():获取线程的优先级
     *   setPriority(int p):设置线程的优先级
     *
     *   说明:高优先级的线程要抢占低优先级线程cpu的执行权。但是只是从概率上讲,高优先级的线程高概率的情况下
     *   被执行。并不意味着只有当高优先级的线程执行完以后,低优先级的线程才执行。
     *
     * @author LXL
     * @create 2019-05-27 18:00
     */
    
    
    class HelloMyThread extends Thread{
        @Override
        public void run() {
    
            for (int i = 0; i < 100; i++) {
                if(i % 2 == 0){
    
    //                try {
    //                    sleep(10);
    //                } catch (InterruptedException e) {
    //                    e.printStackTrace();
    //                }
    
                    System.out.println(Thread.currentThread().getName() + ":" + getPriority() + ":" + i);
                }
    
    //            if(i % 2 == 0){
    //                this.yield();
    //            }
            }
    
        }
    
        public HelloMyThread(String name){
            super(name);
        }
    }
    
    
    public class ThreadMethodTest {
        public static void main(String[] args) {
    
            HelloMyThread h1 = new HelloMyThread("Thread:1");
    
    //        h1.setName("线程一");
    
            h1.start();
    
            //设置分线程的优先级
            h1.setPriority(Thread.MAX_PRIORITY);
    
            //给主线程命名
            Thread.currentThread().setName("主线程");
            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    
            for (int i = 0; i < 100; i++) {
                if(i % 2 == 0){
                    System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i);
                }
    
    //            if(i == 20){
    //                try {
    //                    h1.join();
    //                } catch (InterruptedException e) {
    //                    e.printStackTrace();
    //                }
    //            }
    
            }
    
            System.out.println(h1.isAlive());
    
        }
    
    }

     

     

    package com.lxl.java;
    
    /**
     *
     * 例子:创建三个窗口卖票,总票数为100张.使用继承Thread类的方式
     *
     * 存在线程的安全问题,待解决。
     **/
    class Window extends Thread{
    
    
        private static int ticket = 100;
        @Override
        public void run() {
    
            while(true){
    
                if(ticket > 0){
                    System.out.println(getName() + ":卖票,票号为:" + ticket);
                    ticket--;
                }else{
                    break;
                }
    
            }
    
        }
    }
    
    
    public class WindowTest {
        public static void main(String[] args) {
            Window t1 = new Window();
            Window t2 = new Window();
            Window t3 = new Window();
    
    
            t1.setName("窗口1");
            t2.setName("窗口2");
            t3.setName("窗口3");
    
            t1.start();
            t2.start();
            t3.start();
    
        }
    }
    package com.lxl.java;
    
    /**
     * 创建多线程的方式二:实现Runnable接口
     * 1. 创建一个实现了Runnable接口的类
     * 2. 实现类去实现Runnable中的抽象方法:run()
     * 3. 创建实现类的对象
     * 4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
     * 5. 通过Thread类的对象调用start()
     *
     *
     * 比较创建线程的两种方式。
     * 开发中:优先选择:实现Runnable接口的方式
     * 原因:1. 实现的方式没有类的单继承性的局限性
     *      2. 实现的方式更适合来处理多个线程有共享数据的情况。
     *
     * 联系:public class Thread implements Runnable
     * 相同点:两种方式都需要重写run(),将线程要执行的逻辑声明在run()中。
     *
     */
    //1. 创建一个实现了Runnable接口的类
    class MThread implements Runnable{
    
        //2. 实现类去实现Runnable中的抽象方法:run()
    
    
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                if(i % 2 == 0){
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                }
            }
        }
    }
    
    
    public class ThreadTest1 {
        public static void main(String[] args) {
            //3. 创建实现类的对象
            MThread mThread = new MThread();
    
            //4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
            Thread t1 = new Thread(mThread);
            t1.setName("线程一");
    
    
            //5. 通过Thread类的对象调用start():① 启动线程 ②调用当前线程的run()-->调用了Runnable类型的target的run()
            t1.start();
    
    
            //再启动一个线程,遍历100以内的偶数
            Thread t2 = new Thread(mThread);
            t2.setName("线程二");
            t2.start();
    
        }
    
    }
    package com.lxl.java;
    
    /**
     * 例子:创建三个窗口卖票,总票数为100张.使用实现Runnable接口的方式
     * 存在线程的安全问题,待解决。
     *
     */
    class Window1 implements Runnable{
    
        private int ticket = 100;
    
        @Override
        public void run() {
            while(true){
                if(ticket > 0){
                    System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);
                    ticket--;
                }else{
                    break;
                }
            }
        }
    }
    
    
    public class WindowTest1 {
        public static void main(String[] args) {
            Window1 w = new Window1();
    
            Thread t1 = new Thread(w);
            Thread t2 = new Thread(w);
            Thread t3 = new Thread(w);
    
            t1.setName("窗口1");
            t2.setName("窗口2");
            t3.setName("窗口3");
    
            t1.start();
            t2.start();
            t3.start();
        }
    
    }
  • 相关阅读:
    wince 下,拨号成功,但不能打开网页的问题
    Wince platform configure filesdetail
    WINCE ERRORMSG
    wince 6 s3c2440 io port opearation
    wince 6 kernel configure files
    赞cnblogs
    WINCE DEBUGMSG
    POJ3249 Test for Job DAG最短路
    HDU4552 怪盗基德的挑战书 KMP | 后缀数组 | 暴力
    HDU4554 叛逆的小明 水题
  • 原文地址:https://www.cnblogs.com/LXL616/p/10934187.html
Copyright © 2011-2022 走看看