public class test extends Thread {
public void run()
{
System.out.println(this.getName());
}
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());
test thread1 = new test();
test thread2 = new test ();
thread1.start();
thread2.start();
}
}
//实现Runnable接口方法实现多线程
/*1. 将实现Runnable接口的类实例化。
2. 建立一个Thread对象,并将第一步实例化后的对象作为参数传入Thread类的构造方法。*/
public class test implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args)
{
test t1 = new test();
test t2 = new test();
//MyThread1线程名称
Thread thread1 = new Thread(t1, "MyThread1");
Thread thread2 = new Thread(t2);
//定义线程名称为MyThread2
thread2.setName("MyThread2");
thread1.start();
thread2.start();
}
}
//4个线程,两个线程对j加1,两个线程对j减1
public class test{
private int j;
public static void main(String[] args){
test t = new test();
ADD add = t.new ADD();
SUB sub = t.new SUB();
for(int i=0;i<2;i++){
Thread t1 = new Thread(add);
t1.start();
Thread t2 = new Thread(sub);
t2.start();
}
}
/*这里add方法和sub方法加synchronized关键字是因为当两个线程同时操作同一个变量时,
* 就算是简单的j++操作时,在系统底层也是通过多条机器语句来实现,所以在执行j++过程也是要耗费时间,
* 这时就有可能在执行j++的时候,另外一个线程H就会对j进行操作,因此另外一个线程H可能操作的可能就
* 不是最新的值了。因此要提供线程同步。
*/
private synchronized void add(){
j++;
System.out.println("1——————"+j);
}
private synchronized void sub(){
j--;
System.out.println("2——————"+j);
}
//加线程
public class ADD implements Runnable{
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<1000;i++){
add();
}
}
}
//减线程
public class SUB implements Runnable{
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<1000;i++){
sub();
}
}
}
}