风也温柔

计算机科学知识库

java多线程开发实例 Java多线程(一)实现多线程

  在Java中,可以用、以及实现多线程

   实现多线程

  用方法那么就是目标类继承()类java多线程开发实例java多线程开发实例 Java多线程(一)实现多线程,然后重写父类的run函数,在执行多线程程序时,使用start函数执行。

   class sellTicket extends Thread{

        private int tickets = 20;
        
        @Override
        public void run() {
            try {
                this.sell();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        public void sell() throws InterruptedException {
            while(tickets>0)
            {
                System.out.println("卖了一张票,现在还有"+--this.tickets);
                Thread.sleep(100);
            }
        }
    }
    public class testThread {
        public static void main(String[] args) throws InterruptedException {
            sellTicket st = new sellTicket();
            st.start();
            int index = 0;
            while(true) {
                System.out.println("--------------");
                Thread.sleep(100);
                if(index++>30)
                    break;
            }
            }

  如果不使用多线程,那么看main函数的话,肯定是先卖票(输出卖票信息),再输出----------,但是使用了多线程以后,就是主线程main函数以及 线程一起运行,得到了如下的结果。

  c开发与java开发_java多线程开发实例_c++ 线程池小实例

   实现多线程

  用实现多线程的方法与是类似的,不同的是这个是 ,在执行多线程时是new一个对象,并将的对象放入对象中,再进行start()。

   class sellTicket implements Runnable{

        private int tickets = 20;
        @Override
        public void run() {
            try {
                this.sell();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        public void sell() throws InterruptedException {
            while(tickets>0)
            {
                System.out.println("卖了一张票,现在还有"+--this.tickets);
                Thread.sleep(100);
            }
        }
    }
    public class testThread {
        public static void main(String[] args) throws InterruptedException {
            sellTicket st = new sellTicket();
            new Thread(st).start();
            int index = 0;
            while(true) {
                System.out.println("--------------");
                Thread.sleep(100);
                if(index++>30)
                    break;
            }
        }

  结果与上一个方法相同

  实现多线程

  实现多线程和上面两种的区别在于多线程操作后可以有返回值,其次,用实现的类的多线程操作写在call()函数中,具体可以看下面代码:

<p><pre>class TestCall implements Callable
{

@Override
public String call() throws Exception {
    for (int i=0;i 0) {
            synchronized (o) {
                if(tickets 0) {
            synchronized (o) {
                if(tickets