我想测试Runnable接口.创建实现接口Runnable的类的实例.然后由同一个实例创建三个线程.观察线程如何共享实例的字段变量. 两个问题:1.为什么两个结果不像"20,19,18 ...... 1,0"的顺序?2.为什么这两个结果彼此不同?(我运行代码两次.) 代码如下:
public class ThreadDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
TestThread tt = new TestThread();
Thread t1 = new Thread(tt);
Thread t2 = new Thread(tt);
Thread t3 = new Thread(tt);
t1.start();
t2.start();
t3.start();
}
}
class TestThread implements Runnable {
public int tickets = 20;
public void run(){
while (tickets >= 0){
System.out.println(Thread.currentThread().getName() + ":the number of tickets is " + tickets--);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我运行代码两次.两个结果如下所示. 第一次:
Thread-1:the number of …Run Code Online (Sandbox Code Playgroud) 下面显示了几种创建字符串的方法.在注释的表达式后面添加问题.
String str = "test";
String str1 = new String(str); //Will it invoke the Constructor of String(String)?
String str2 = new String("test");//Will it invoke the Constructor of String(String)?
String str3 = str; //Which Constructor will it invoke? Or str3 only reference to str and "test" without being constructed?
String str4 = "test";//Which Constructor will it invoke? Or str4 only reference to str and "test" without being constructed?
String strnew = new String("testnew");//Will this expression create "testnew" in String Constant Pool …Run Code Online (Sandbox Code Playgroud)