刚刚在看张老师讲解的线程同步锁视频,遇到一个疑问,发上来大家共同探讨下:
代码如下:- package cn.andy.java.thread;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class LockTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- new LockTest().init();
-
- }
- public void init(){
- final Outputer output=new Outputer();
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- while(true){
- try {
- Thread.sleep(10);
- } catch (Exception e) {
- // TODO: handle exception
- }
- output.output("andy.wei");
- }
- }
- }).start();
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- while(true){
- try {
- Thread.sleep(10);
- } catch (Exception e) {
- // TODO: handle exception
- }
- output.output2("cindy.li");
- }
- }
- }).start();
- }
- static class Outputer{
- Lock lock=new ReentrantLock();
- public void output(String name){
- int len=name.length();
- lock.lock();
- try {
- for (int i = 0; i < len; i++) {
- System.out.print(name.charAt(i));
- }
- System.out.println();
- } catch (Exception e) {
-
- }finally{
- lock.unlock();
- }
- }
- public synchronized void output2(String name){
- int len=name.length();
- //lock.lock();
- try {
- for (int i = 0; i < len; i++) {
- System.out.print(name.charAt(i));
- }
- System.out.println();
- } catch (Exception e) {
- // TODO: handle exception
- }
- // finally{
- // lock.unlock();
- // }
-
- }
- public static synchronized void output3(String name){
- int len=name.length();
-
- for (int i = 0; i < len; i++) {
- System.out.print(name.charAt(i));
- }
- System.out.println();
- }
- }
- }
复制代码 output方法我用的是锁,output2中用的是同步关键字,测试打印的时候出现output中的未打印完成就开始了output2中的打印输出,导致数据打印不完整,有点疑惑,大家一起帮忙看看吧,谢谢。
|
|