其他分享
首页 > 其他分享> > 多线程之二

多线程之二

作者:互联网

线程通信

/**
 * 两个线程交替打印1-100之间的数字
 */
public class ThreadTest3 {
    public static void main(String[] args) {
        Demo04 demo04 = new Demo04();
        Thread t1 = new Thread(demo04);
        Thread t2 = new Thread(demo04);
        t1.setName("线程一");
        t2.setName("线程二");
        t1.start();
        t2.start();
    }
}
class Demo04 implements Runnable{
    private static int i=1;
    @Override
    public void run() {
        while (true){
            synchronized (this){
                //唤醒所有线程,首次执行时无效果
                notifyAll();
                if (i<=100){
                    System.out.println(Thread.currentThread().getName()+":"+i);
                    i++;
                    try {
                        //使当前线程沉睡。可以被notifyAll()和notify()唤醒
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    break;
                }
            }
        }
    }
}

wait() 与 notify() 和 notifyAll()

这三个方法只有在synchronized方法或synchronized代码块中才能使用,否则会报
java.lang.IllegalMonitorStateException异常。


面试题:sleep() 和 wait()的异同?


JDK5.0新增的线程创建方式

实现Callable接口

public class ThreadTest4 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Demo05 demo05 = new Demo05();
        FutureTask futureTask = new FutureTask(demo05);
        new Thread(futureTask).start();
        Object o = futureTask.get();
        System.out.println(o);
    }
}

class Demo05 implements Callable{
    @Override
    public Object call() throws Exception {
        int sum =0;
        for (int i = 1; i <=100 ; i++) {
            if (i%2==0){
                System.out.println(i);
                sum+=i;
            }
        }
        return sum;
    }
}

线程池

好处


实现

public class Pool {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(10);
        service.execute(new Demo06());
        service.shutdown();
    }
}
class Demo06 implements Runnable{
    @Override
    public void run() {
        for (int i = 1; i <=100 ; i++) {
            if (i%2==0){
                System.out.println(i);
            }
        }
    }
}

标签:Thread,class,之二,线程,new,多线程,public,wait
来源: https://www.cnblogs.com/Boerk/p/16094993.html