有没有yield()、sleep()、wait()、join()、run和start区别代码实例代码案例 找不到 可以运行的 不要 文档
java之Thread线程相关 代码案例代码案例
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- 来时路去征途 2017-10-12 02:11关注
这是我做练习的时候写的代码,你可以参考下,
/**
*run(),start(),join(),sleep(),yield();练习
*/
public class ThreadTest {
private int i=0;
private Object o = new Object();
static class Mythread extends Thread{
public void run() {
System.out.println("0当前线程ID:"+Thread.currentThread().getId());
}
}static class Mythread1 implements Runnable{ public void run() { System.out.println("1当前线程ID:"+Thread.currentThread().getId()); } } public static void main(String[] args) throws InterruptedException { /*System.out.println("主线程:"+Thread.currentThread().getId()); Mythread mythread = new Mythread(); mythread.run(); mythread.start(); System.out.println("******************************************************"); System.out.println("主线程:"+Thread.currentThread().getId()); Mythread1 mythread1 = new Mythread1(); mythread1.run(); Thread thread = new Thread(mythread1); thread.start();*/ //mythread1.start(); ThreadTest test = new ThreadTest(); /*SleepClass p =test.new SleepClass(); SleepClass p1 = test.new SleepClass(); p.start(); p1.start();*/ /*YeildClass y = test.new YeildClass(); y.start();*/ //启动子线程 new JoinClass("new Thread").start(); for(int i=0;i<10;i++){ if(i==5){ Thread th = new JoinClass("thead"); th.start(); th.join(); } System.out.println(Thread.currentThread().getName()+" "+i); } } class SleepClass extends Thread{ @Override public void run() { synchronized (o){ i++; System.out.println("i:"+i); try { System.out.println("线程:"+ Thread.currentThread().getName()+"进入睡眠"); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程"+Thread.currentThread().getName()+"睡眠结束"); i++; System.out.println("i:"+i); } } } class YeildClass extends Thread{ public void run() { long benginTime = System.currentTimeMillis(); int count = 0; for(int i=0;i<500000;i++){ count = count +i; Thread.yield(); } long endTime = System.currentTimeMillis(); System.out.println("用时:"+(endTime-benginTime)); } } static class JoinClass extends Thread{ public JoinClass(String name){ super(name); } public void run() { for (int i =0;i<5;i++){ System.out.println(this.getName()+" "+i); } } }
}
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 求差集那个函数有问题,有无佬可以解决
- ¥15 【提问】基于Invest的水源涵养
- ¥20 微信网友居然可以通过vx号找到我绑的手机号
- ¥15 寻一个支付宝扫码远程授权登录的软件助手app
- ¥15 解riccati方程组
- ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
- ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
- ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
- ¥50 树莓派安卓APK系统签名
- ¥65 汇编语言除法溢出问题