A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Fangjie   /  2016-6-7 13:30  /  1269 人查看  /  25 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

车前子008 发表于 2016-6-9 11:56
class Shangche implements Runnable{
               
        static int persons = 70;

试了一下,这种方法虽然能保证数据同步,如果在while上面加锁,最后都是只一个线程走完,可以在run方法里调用其它的线程吗
回复 使用道具 举报
车前子008 发表于 2016-6-9 11:56
class Shangche implements Runnable{
               
        static int persons = 70;

问题解决了,这种写法可行!
        public static void main(String[] args) throws InterruptedException {
                        ByBus b = new ByBus();
                        Thread t1 = new Thread(b, "线程一");
                        Thread t2 = new Thread(b, "线程二");
                        t1.start();
                        t2.start();
                        t1.join();
                        t2.join();
                        System.out.println("执行完毕");
                }
        }

        class ByBus implements Runnable {
               
                public static int  persons = 70;
                public void run() {               
                        while (true) {
                        synchronized (ByBus.class) {
                                if(persons<=0)
                                        break;
                                        System.out.println(Thread.currentThread().getName() +-- persons);
                                }
                        }                               
                }
回复 使用道具 举报
把锁里的 Person换成this           synchronize(this)
回复 使用道具 举报
写错了  是  synchronized(this)
回复 使用道具 举报
按照你代码的意思,感觉没有问题。。。。。
回复 使用道具 举报
何亚辉 发表于 2016-6-7 14:12
package com.heima.IO;

import java.io.IOException;

六六六。。。
回复 使用道具 举报
12
您需要登录后才可以回帖 登录 | 加入黑马