线程之wait,sleep区别之是否会影响到其他线程

wait和sleep的区别:(执行权和锁区分)

wait:可指定等待的时间,不指定须由notify或notifyAll唤醒。

       线程会释放执行权,且释放锁。

sleep:必须制定睡眠的时间,时间到了自动处于临时(阻塞)状态。

       即使睡眠了,仍持有锁,不会释放执行权。

1. 不论是wait还是sleep,都是将线程堵塞掉,但是该线程的堵塞是无法影响到其他线程的执行

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_default_widgets);
        ButterKnife.bind(this);
        {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        FlyLineStaticValueHelper.waypointMissionOperator.downloadMission(new CommonCallbacks.CompletionCallback() {
                            @Override
                            public void onResult(DJIError djiError) {
                                try {
                                    String dir = Environment.getExternalStorageDirectory().toString();
                                    File file = new File(dir + File.separator + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'");
                                    if (!file.exists())
                                        file.mkdir();
                                    file = new File(dir + File.separator + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'" + File.separator + "123.txt");
                                    if (!file.exists())
                                        file.createNewFile();

                                    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
                                    bufferedWriter.write("downloadMission");
                                    bufferedWriter.close();
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                ToastUtils.showToast("downloadMission");
                            }
                        });
                    }
                }).start();

            }
            try {
                Thread.currentThread().sleep(500000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
}

上段代码,虽然UI线程被阻塞了500000毫秒,但是123.txt文件依旧会在睡眠过程中被创建。

你可能感兴趣的:(Android,JAVA)