天天看點

線程之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檔案依舊會在睡眠過程中被建立。