多线程(二)——线程的基本操作

线程的状态转换
http://blog.csdn.net/pcceo1/article/details/52444730
1.停止线程
Thread.stop(),已经被弃用的方法,不推荐使用。

public class ThreadStop implements Runnable{
    @Override
    public void run() {
        try {
            System.out.println("开始");
            Thread.sleep(10000);
            System.out.println("线程睡了10秒");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Thread thread = new Thread(new ThreadStop());
        //启动线程
        thread.start();
        //停止线程
        thread.stop();
    }

}

这个程序执行的时候在控制台并没有输出什么,说明线程在启动后,还没有开始执行方法体,线程已经被停止了。
尝试在主线程中睡眠2秒钟,再停止线程。

package cn.zengzehao.thread;

public class ThreadStop implements Runnable{
    @Override
    public void run() {
        try {
            System.out.println("开始");
            Thread.sleep(10000);
            System.out.println("线程睡了10秒");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Thread thread = new Thread(new ThreadStop());
        thread.start();
        try {
        //休眠2秒
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        thread.stop();
    }

}

程序执行后,在控制台输出了“开始”,2秒钟后结束线程。

通过上面的例子,使用Thread.stop()方法停止线程,不管线程的方法体有没有执行完,都会被停止掉,这样子会容易导致数据不一致的问题,比如在一个线程中写入数据,写到一半线程就被停止掉了。

2.线程的中断
线程被中断,并不是真正去中断线程,而是给线程设置了一个标志位,在线程执行的时候可以检查线程是否被设置了中断。

public void interrupt() // 中断线程
public boolean isInterrupted() // 判断是否被中断
public static boolean interrupted() // 判断是否被中断,并清除当前中断状态

直接看程序吧

package cn.zengzehao.thread;

public class ThreadInterrupted implements Runnable{
    public static void main(String[] args) {
        Thread thread = new Thread(new ThreadInterrupted());
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        thread.interrupt();
        //thread.stop();
    }
    @Override
    public void run() {
        for(;;){
            System.out.println("线程开始执行");
            System.out.println("line22"+Thread.currentThread().isInterrupted());
            if(Thread.currentThread().isInterrupted()){
                System.out.println("线程已经被中断");
                break;
            }
            long sum = 0;
            for(long i=0;i<100000;i++){
                sum+=i;
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally{
                System.out.println("line37"+Thread.currentThread().isInterrupted());
                //设置中断状态,抛出异常后会清除中断标记位
                Thread.currentThread().interrupt();
                System.out.println("line39"+Thread.currentThread().isInterrupted());
            }
            System.out.println(sum);
        }
    }

}

执行程序,如果调用interrupted(),线程会把方法体剩下的执行完,如果是调用stop(),线程会直接就结束。stop()方法太暴力了,不推荐使用。

3.线程的挂起和继续执行线程
– suspend()不会释放锁
– 如果加锁发生在resume()之前 ,则死锁发生

4.等待线程的结束 jion()
在多线程中,经常需要等待其他线程执行完,再进行下面的操作,这个时候就需要用到jion()

package cn.zengzehao.thread;

public class ThreadJion implements Runnable{
    public volatile static int i =0;
    public static void main(String[] args) {
        Thread thread = new Thread(new ThreadJion());
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main方法"+i);
    }

    @Override
    public void run() {
        for(i=0;i<1000000;i++);
        System.out.println("方法内:"+i);
    }
}

如果不使用jion(),运行结果是

main方法0
方法内:1000000

使用jion(),运行结果是

main方法1000000
方法内:1000000

5.线程的谦让 yield()
一个调用yield()方法的线程告诉虚拟机它乐意让其他线程占用自己的位置。

6.线程等待wait()
7.线程的唤醒notify()和notifyAll()

package cn.zengzehao.thread;

public class ThreadWaitAndNotify {
    final static Object object= new Object();
    public static void main(String[] args) {
        Thread t1 = new Thread(new T1());
        Thread t2 = new Thread(new T2());
        t1.start();
        t2.start();
    }
    static class T1 implements Runnable{
        @Override
        public void run() {
            synchronized (object) {
                System.out.println("T1线程开始");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("T1线程结束");
            }

        }

    }
    static class T2 implements Runnable{

        @Override
        public void run() {
            synchronized (object) {
                System.out.println("T2线程开始");
                object.notify();
                System.out.println("T2线程结束");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

}

notify()会随机唤醒一个在等待的线程。
notifyAll()会唤醒全部的线程。

package cn.zengzehao.thread;

public class ThreadWaitAndNotify {
    final static Object object= new Object();
    public static void main(String[] args) {
        Thread t1 = new Thread(new T1());
        Thread t2 = new Thread(new T2());
        Thread t3 = new Thread(new T3());
        Thread t4 = new Thread(new T4());
        t1.start();
        t3.start();
        t4.start();
        //休眠100毫秒,为了唤醒线程可以在其他线程都已经启动
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        t2.start();
    }
    static class T1 implements Runnable{
        @Override
        public void run() {
            synchronized (object) {
                System.out.println("T1线程开始");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("T1线程结束");
            }

        }

    }
    static class T3 implements Runnable{
        @Override
        public void run() {
            synchronized (object) {
                System.out.println("T3线程开始");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("T3线程结束");
            }

        }

    }

    static class T4 implements Runnable{
        @Override
        public void run() {
            synchronized (object) {
                System.out.println("T4线程开始");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("T4线程结束");
            }

        }

    }
    static class T2 implements Runnable{

        @Override
        public void run() {
            synchronized (object) {
                System.out.println("T2线程开始");
                object.notify();
                System.out.println("T2线程结束");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C++ 中,我们可以使用线程库来实现多线程编程。线程的挂起、唤醒与终止是多线程编程中非常重要的一部分。 线程的挂起也称为线程的休眠,它可以让线程停止运行一段时间,等待某个条件满足后再继续运行。在 C++ 中,我们可以使用 std::this_thread::sleep_for() 函数来实现线程的挂起,该函数可以让当前线程挂起一段时间,例如: ```cpp #include <chrono> #include <thread> int main() { // 挂起当前线程 1 秒钟 std::this_thread::sleep_for(std::chrono::seconds(1)); return 0; } ``` 线程的唤醒可以通过条件变量来实现,条件变量是一种同步机制,用于在线程之间传递信号。在 C++ 中,我们可以使用 std::condition_variable 类来创建条件变量,然后使用 wait() 函数来挂起线程等待条件变量的信号,使用 notify_one() 函数来唤醒一个等待条件变量的线程,例如: ```cpp #include <condition_variable> #include <mutex> #include <thread> std::condition_variable cv; std::mutex mtx; bool ready = false; void worker_thread() { // 等待条件变量的信号 std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [](){ return ready; }); // 条件满足后继续执行 // ... } int main() { // 唤醒等待条件变量的线程 { std::lock_guard<std::mutex> lock(mtx); ready = true; } cv.notify_one(); return 0; } ``` 线程的终止可以使用 std::thread::join() 函数来实现,该函数可以让当前线程等待另一个线程执行完成后再继续执行,例如: ```cpp #include <thread> void worker_thread() { // ... } int main() { std::thread t(worker_thread); // 等待 worker_thread 执行完成 t.join(); return 0; } ``` 另外,线程的终止还可以使用 std::thread::detach() 函数来实现,该函数可以让当前线程与创建的线程分离,使得两个线程可以独立运行,例如: ```cpp #include <thread> void worker_thread() { // ... } int main() { std::thread t(worker_thread); // 分离线程,使得两个线程可以独立运行 t.detach(); return 0; } ``` 需要注意的是,分离线程后,主线程不能再使用 join() 函数等待子线程执行完成,否则会导致程序崩溃。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值